Lauren Quantrell
Lauren Quantrell

Reputation: 2669

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 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];

}


}

Upvotes: 0

Views: 181

Answers (2)

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39988

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.

Upvotes: 1

Richard Brightwell
Richard Brightwell

Reputation: 3012

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.

Upvotes: 0

Related Questions