1.NSOperation NSOperationQueue
nsoperation里用neurlconnection的话,必须是同步的??????
使用NSThread类的detachNewTheadSelector:toTagaet:withObject方法创建一个线程:
[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,调出主线程中的方法去刷新。
http://hi.baidu.com/ncudlz/blog/item/9ce32d09f5dca3a12fddd461.html
在线程执行函数中,使用
do {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}while(done); 阻塞线程结束.
在主线程中,runloop默认是开启的。非主线程中,如果要用到runloop,必须手动开启runloop。
2. 延时 NSThread
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0f]];//暂停一秒,Blocks the current thread until the time specified.
[NSThread sleepForTimeInterval:0.5f];
sleep(int秒);
3.CFRunLoopRef。
CFRunLoopRef currentLoop = CFRunLoopGetCurrent(); //获得当前线程的循环,而不是创建新的线程。
CFRunLoopRun(); // Wait for response ,此时用户在界面上的操作也是可以响应的。
CFRunLoopStop(currentLoop);//可在用户或点击,或回调响应时调用,停止循环,将控制权返还给调用方法。
iPhone 模态对话框 立即返回结果
http://blog.csdn.net/xianpengliu/article/details/6591624
实现方便的连续动画
http://www.iteye.com/topic/1113006
4. 不用scheduled方式初始化的,需要手动addTimer:forMode: 将timer添加到一个runloop中。
而scheduled的初始化方法将以默认mode直接添加到当前的runloop中.
scheduledTimerWithTimeInterval立即启动计时
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];
timerWithTimeInterval只生成一个timer,并不启动计时
NSTimer *myTimer = [NSTimer timerWithTimeInterval:3.0 target:selfselector:@selector(timerFired:) userInfo:nil repeats:NO];
将生成的timer加入到currentRunLoop,即启动了计时
[[NSRunLoop currentRunLoop]addTimer:myTimer forMode:NSDefaultRunLoopMode];
另外,如想不等待立即执行然后再周期性执行,可以先执行一次目标函数,再把timer添加到Loop中。
5.scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: 注意点解析
target参数: The target object is retained by the timer and released when the timer is invalidated
提防出现互相retain的现象。如果target和timer互相retain,就形成了死锁情况,要保证在target的dealloc函数将被执行时,timer不再retain target。否则可能target的dealloc函数不会被执行,或者系统崩溃。
有时应急处理崩溃问题,采用以下方法:把会引起崩溃的代码段放到一个消息响应处理中,在原处发起这个消息。如果如果触发起消息时,这个消息的注册被取消了,则发起的这个消息不会有响应了。
6.