`
woainike
  • 浏览: 79147 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
最近访客 更多访客>>
社区版块
存档分类
最新评论

performSelectorOnMainThread 和detachNewThreadSelector区别.

阅读更多

举例说明怎么简单的创建一个子线程。

用到的类是NSThread类,这里使用detachNewTheadSelector:toTagaet:withObject创建一个线程。

函数setupThread:(NSArray*)userInfor。通过userInfor将需要的数据传到线程中。

函数定义:

-(void)setupThread:(NSArray*)userInfor{

   [NSThread detachNewThreadSelector:@selector(threadFunc:) toTarget:self withObject:(id)userInfor];

}

- (void)threadFunc:(id)userInfor{

   NSAutoreleasePool*pool = [[NSAutoreleasePool alloc] init];

   //。。。。需要做的处理。

   //这里线程结束后立即返回

  [self performSelectorOnMainThread:@selector(endThread) withObject:nil waitUntilDone:NO];

  [pool release];

}

performSelectorOnMainThread通知主线程执行函数endThread。也可以使用performSelector:onThread:withObject:waitUntil 通知某线程执行线程结束后的处理。

线程内不要刷新界面。如果需要刷新界面,通过performSelectorOnMainThread,调出主线程中的方法去刷新。

 

例如,启动一个线程下载图片:

//启动线程

[NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:url];

//线程函数

- (void) downloadImage:(NSString*)url{
    
    _subThreed = [NSThread currentThread];
    
    self.uploadPool = [[NSAutoreleasePool alloc] init];
    self.characterBuffer = [NSMutableData data];
    done = NO;
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURLURLWithString:url]];
    
    self.connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    [self performSelectorOnMainThread:@selector(httpConnectStart) withObject:nil waitUntilDone:NO];
    if (connection != nil) {
        do {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        } while (!done);
    }
    
    self.photo = [UIImage imageWithData:characterBuffer];
    

    //下载结束,刷新
    [self performSelectorOnMainThread:@selector(fillPhoto) withObject:nil waitUntilDone:NO];
    
    // Release resources used only in this thread.
    self.connection = nil;
    [uploadPool release];
    self.uploadPool = nil;
    
    _subThreed = nil;
}


#pragma mark NSURLConnection Delegate methods

/*
 Disable caching so that each time we run this app we are starting with a clean slate. You may not want to do this in your application.
 */

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {

    return nil;
}

// Forward errors to the delegate.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    done = YES;
    [self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO];
    [characterBuffer setLength:0];
    
}

// Called when a chunk of data has been downloaded.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Process the downloaded chunk of data.
 
    [characterBuffer appendData:data];
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
    [self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO];
    // Set the condition which ends the run loop.
    done = YES; 
}

分享到:
评论
4 楼 woainike 2012-04-24  
hhb19900618 写道
兄弟 我没理解 _subThreed = [NSThread currentThread];你的这行代码是干啥?你根本没有利用 _subThreed 这个成员变量啊?


Returns the thread object representing the current thread of execution.

+ (NSThread *)currentThread
Return Value
A thread object representing the current thread of execution.


这里面的片段代码,可不用关心。
3 楼 hhb19900618 2012-04-16  
兄弟 我没理解 _subThreed = [NSThread currentThread];你的这行代码是干啥?你根本没有利用 _subThreed 这个成员变量啊?
2 楼 woainike 2012-03-29  
hhb19900618 写道
你好 我想问一下: //下载结束,刷新
    [self performSelectorOnMainThread:@selector(fillPhoto) withObject:nil waitUntilDone:NO];  它是怎么知道 下载结束了?难道performSelectorOnMainThread自动知道子线程运行完毕?



- (void)connectionDidFinishLoading:(NSURLConnection *)connection

这是个delegate。
你实现这个方法后,当connection结束后就会被执行的。
1 楼 hhb19900618 2012-03-28  
你好 我想问一下: //下载结束,刷新
    [self performSelectorOnMainThread:@selector(fillPhoto) withObject:nil waitUntilDone:NO];  它是怎么知道 下载结束了?难道performSelectorOnMainThread自动知道子线程运行完毕?

相关推荐

    iOS开发学习之iOS多线程和RunLoop.pdf

    使用NSThread,我们可以创建一个新的线程来执行特定的任务,例如使用`[NSThread start]`、`[NSThread detachNewThreadSelector:toTarget:withObject:]`方法来启动一个新线程。通过NSThread,我们还可以在主线程上...

    swift异步下载网络图片

    或者,如果使用了`detachNewThreadSelector`,则可以将UI更新操作作为目标方法的一部分,使用`self.performSelectorOnMainThread`。 现在,让我们讨论一下“一步下载”的概念。在某些情况下,可能需要一次性下载多...

    多线程_IOS应用源码.zip

    此外,源码可能还涵盖了如何在主线程和后台线程之间切换,以更新UI(如使用`DispatchQueue.main.async`或`performSelectorOnMainThread`),因为所有的UI操作都必须在主线程上进行。 总之,"多线程_IOS应用源码.zip...

    多线程技术在iOS开发中的使用.doc

    2. **NSThread**:可以直接创建线程,通过`detachNewThreadSelector:toTarget:withObject:`或`initWithTarget:selector:object:`方法,指定执行的selector、目标对象和参数。不过,线程的生命周期需要手动管理。 3....

    IOS两个精典的关于多线程的例子代码

    1. **+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument;** 这个类方法用于创建并启动一个新线程,执行指定的目标对象上的选择器方法。选择器、目标对象和可选参数是...

    NSThreadAndBlockDemo

    另一种是通过`detachNewThreadSelector:toTarget:withObject:`方法,指定执行的方法、目标对象以及参数。 `Block`,又称为闭包,是Objective-C的一个强大特性,它允许我们将一段代码封装起来,作为一个可传递的对象...

    IOS部分面试题

    - 创建线程:可以通过NSThread的`detachNewThreadSelector:toTarget:withObject:`,GCD的`dispatch_async`,或者NSOperationQueue来实现。 - 主线程执行:`[someMethod performSelectorOnMainThread:@selector...

    NSThread多线程

    4. 线程同步:如果你需要在线程间进行通信,可以使用`NSThread`s的`detachNewThreadSelector:toTarget:withObject:`方法来启动新线程,或者使用NSLock、NSCondition等同步原语来避免竞态条件。 5. 资源管理:与其他...

    ios开发记录

    //initWithNibName将控制器绑定xib的方法,如果xib的名称和控制器的类名称相同的时候,直接写init(会自动绑定同名的xib)就可以,如果xib的名称和类名称不同的话,必须手动调用此方法来进行绑定 ...

    iOS多线程简单介绍

    [NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:@"hi"]; ``` 此方法会在一个新的线程中执行`doSomething:`方法,并传入参数`"hi"`。 2. **实例方法**: ```objective-c ...

    实例解析iOS应用多线程开发中NSthread类的用法

    2. 在主线程上执行操作:`performSelectorOnMainThread:withObject:waitUntilDone:` 通常用于更新UI,确保在主线程执行。 3. 在当前线程执行操作:`performSelector:withObject:` 如果不需要切换线程,可以直接调用...

Global site tag (gtag.js) - Google Analytics