views:

245

answers:

2

I wanted to know how to use threads in Cocoa. I'm new to this so I don't understand the documentation that well.

The Top half of the code is for timing and the bottom half is for the date. Can anyone show me how to use a single thread and how to use 2 threads to handle both operations.

NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc] init] autorelease];
[timeFormatter setDateStyle:NSDateFormatterNoStyle];
[timeFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSDate *stringTime = [NSDate date];
NSString *formattedDateStringTime = [timeFormatter stringFromDate:stringTime];
time.text = formattedDateStringTime;

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *stringDate = [NSDate date];
NSString *formattedDateStringDate = [dateFormatter stringFromDate:stringDate];
date.text = formattedDateStringDate;
+2  A: 

Threads are pretty easy to implement. A minute to learn, a lifetime to master, they say.

This should get you started:

http://cocoasamurai.blogspot.com/2008/04/guide-to-threading-on-leopard.html

(applies to iPhone OS as well)

Corey Floyd
That's a really excellent document. I have found that NSOperations in combination with NSOperationQueue are a fantastic resource...
Kendall Helmstetter Gelner
I forgot to mention one reason they are so excellent is that you don't have to worry about creating new autorelease pools, that is done for you.
Kendall Helmstetter Gelner
Yep we are very fortunate to have many awesome developers in the Cocoa world who don't mind compiling and sharing information that would otherwise take quite a while to gather and understand.
Corey Floyd
+1  A: 

For quick stuff, the easiest way to do it is put the code into separate methods, then call:

[self performSelectorInBackground:@selector(formatTime) withObject:nil];
[self performSelectorInBackground:@selector(formatDate) withObject:nil];

You may need to put an NSAutoreleasePool in the method to stop memory leaks.

Also, as has been said by other people, date formatting isn't really something you should be doing in a separate thread.

Tom Dalling