开发者

Newbie Question About Running a Process On a New Thread

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 as开发者_如何学Cking 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];

}


}


There is some problem i think, @selector expects a selector not a method call. So the correct one should be like this

- (void)applicationDidFinishLaunching:(UIApplication *)application { 

    [NSThread detachNewThreadSelector:@selector(parseXML:) 
        toTarget:objXMLParser
        withObject:requestStr];

}

//here the taget is the object whose selector you are passing. so you can't use self there as parseXML: is the method of XMLParser class

// *** XMLParser.m ***

-(void)parseXML {

    // Dunno why NSAutoreleasePool is needed but apparently it is

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

    // . . . my code

    [pool release];

}

// 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜