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















    无论生活、还是技术,一切都不断的学习和更新~~~努力~
  • 相关阅读:
    如何建一个SAM
    3.Telegraf自定义脚本模块
    2.Influxdb函数
    1.自动化运维监控
    7.mysql8.0版本MGR搭建
    6.mysql存储过程
    5.innodb B+tree索引
    4.mysql profile的使用方法
    3.mysql小表驱动大表的4种表连接算法
    2.mysql explain命令详解
  • 原文地址:https://www.cnblogs.com/GoGoagg/p/2296043.html
Copyright © 2020-2023  润新知