NSthread与NStimer和NSNotifcation之间的区别?

时间:2010-03-24 07:18:03

标签: iphone

以下代码之间有什么区别

1)

 [NSThread detachNewThreadSelector:@selector(myFunction) toTarget:self withObject:thename];

2)

[NSTimer scheduledTimerWithTimeInterval:1.0
                                 target:self 
                               selector:@selector(myFunction:) 
                               userInfo:nil 
                                repeats:NO];

3)

[self performSelector:@selector(myFunction) withObject:nil afterDelay:myDelay]; 

4)

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunction:) name:thename object:nil];

1 个答案:

答案 0 :(得分:6)

  1. 在单独的线程中执行选择器。如果要在被调用函数中自动释放对象,则需要设置自己的自动释放池。您无法直接使用GUI,但如果该功能需要很长时间才能完成,则不会阻止它。使用performSelectorInBackground:的{​​{1}}撰写可能更好。

  2. 主线程延迟后运行选择器。不需要自动释放池(您使用的是默认池),您可以直接使用GUI,但如果该功能需要很长时间才能完成,您将阻止它。

  3. 非常喜欢2。

  4. 完全不同,请参阅NSNotificationCenter的文档。您告诉默认通知中心您要接收NSObject(=任何对象)发送的名称thename的所有通知。发布此类通知后,通知中心将调用nil并向其传递描述该事件的myFunction实例。

  5. 我希望我把一切都搞定,前三点有点棘手。