cocoa下的多线程实践


线程相关的类:NSThread ,NSOperation ,NSOperationQueue

在实际应用中可以分为2种方式:
1、使用NSThread
2、使用NSOperation,NSOperationQueue

前者,和过往window下的线程学习类似;后者,是mac以队列的方式来新建线程。

针对前者,写部分代码:

- (void)threadFunc:(id)info
{
NSLog(@"%@ ,run thread" ,info);
}

- (void)viewDidLoad
{
[super viewDidLoad];
[NSThread detachNewThreadSelecor:@selector(threadFunc:) toTarget:self withObject:nil];
}


针对后者,也写些代码:

@interface PageLoadOperation : NSOperation

@property (retain) NSURL *targetURL;

- (id)initWithUrl:(NSURL *)url;

@end

 

@implementation PageLoadOperation

@synthesize targetURL;

- (id)init
{
self = [super init];
if (self)
{
self->targetURL = nil;
}

return self;
}

- (id)initWithUrl:(NSURL *)url
{
self = [self init];
if (self)
{
self->targetURL = url ? [url retain] : nil;
}

return self;
}

- (void)dealloc
{
if (self.targetURL)
[self->targetURL release];
[super dealloc];
}

- (void)main
{
NSLog(@"main run");

if (self.targetURL == nil)
return;

NSError *error = nil;
NSData *data = [[[NSData alloc] initWithContentsOfURL:self.targetURL options:NSDataReadingMappedAlways error:&error] autorelease];

if (error)
NSLog(@"error infomation : %@" ,erro);
else if (data)
{
NSLog(@"%@" ,data);
}
}

@end


调用有两种:
1、直接调用

    PageLoadOperation *p = [[PageLoadOperation alloc] initWithUrl:[NSURL URLWithString:@"http://www.sohu.com"]];
//p.targetURL = [NSURL URLWithString:@"http://www.baidu.com"];
[p start];
[p release];


2、使用NSOperationQueue

NSOperationQueue *_queue = [[NSOperationQueue alloc] init];

PageLoadOperation *plo = [[PageLoadOperation alloc] initWithUrl:[NSURL URLWithString:url]];
plo.delegate = self;
[_queue addOperation:plo];

[plo release];

[_queue release];














你可能感兴趣的:(cocoa下的多线程实践)