Zeeshan Raja
Zeeshan Raja

Reputation: 145

Using NSThreads in Cocoa?

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;

Upvotes: 0

Views: 516

Answers (2)

Tom Dalling
Tom Dalling

Reputation: 24145

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.

Upvotes: 1

Corey Floyd
Corey Floyd

Reputation: 25969

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)

Upvotes: 3

Related Questions