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];














转载于:https://www.cnblogs.com/GoGoagg/archive/2011/12/21/2296043.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值