关于在新线程上运行进程的新手问题
到目前为止,我的应用程序非常简单,但现在我发现我需要在单独的线程上运行一个进程,所以这是一个 xCode 101 问题,询问我如何做到这一点。
我想运行一个在应用程序启动时运行的进程,因此我想在 AppDelegate.applicationDidFinishLaunching 中执行它。
根据我所读到的内容,我认为这就是我需要做的全部,但如果我错了,请纠正我。
// *** AppDelegate.m ****
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[NSThread detachNewThreadSelector:@selector([XMLParser parseXML:])
toTarget:self
withObject:requestStr];
}
// *** XMLParser.m ***
-(void)parseXML {
// Dunno why NSAutoreleasePool is needed but apparently it is
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// . . . my code
[pool release];
}
}
So far my apps have been pretty simple, but now I'm finding I need to run a process on a separate thread, so this is an xCode 101 question asking how I do that.
I want to run a process that runs when the app launches, so I want to execute it in AppDelegate.applicationDidFinishLaunching.
From what I've read, I think this is all I need to do, but please correct me if I'm wrong.
// *** AppDelegate.m ****
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[NSThread detachNewThreadSelector:@selector([XMLParser parseXML:])
toTarget:self
withObject:requestStr];
}
// *** XMLParser.m ***
-(void)parseXML {
// Dunno why NSAutoreleasePool is needed but apparently it is
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// . . . my code
[pool release];
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为存在一些问题,@selector 期望选择器而不是方法调用。所以正确的应该是这样的
// 需要自动释放池,因为它是一个单独的线程,并且您的代码可能使用一些可可或您自己的调用/方法/代码来自动释放对象,这就是为什么您必须保留自动释放池对于那些自动释放的对象。如果您的代码不使用任何
[obj autorelease]
语句或不自动释放对象,在这种情况下您可以省略自动释放池语句,但保留它是一个好习惯。There is some problem i think, @selector expects a selector not a method call. So the correct one should be like this
// Autorelease pool is needed as it is a separate thread, and your code might use some cocoa or your own calls/methods/code that autoreleases an object that's why you have to keep an auto release pool for those autoreleased objects. if your code doesn't use any
[obj autorelease]
statement or doesn't auto release an object in that case you can omit auto release pool statements, but it's a good practice to keep it.我没有使用你描述的方法,但使用了 NS 操作。它支持并发和非并发操作,并且易于使用。
I have not used the method you describe, but have used NSOpertaions. It supports but concurrent and non-concurrent operations and is easy to use.