I have a Thread called 10 times:
[NSThread detachNewThreadSelector:@selector(workInBackground:) toTarget:self withObject:sendArray];
This is the “workInBackground” method:
- (void)workInBackground:(NSArray*)dataArray{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // create release pool
// display dataArray sent from Main Thread
NSLog(@"%i, %@", [[dataArray objectAtIndex:0] intValue], [dataArray objectAtIndex:1]);
// Fetch data from URL
NSString *myURL = [NSString stringWithFormat:@"http://somesite.com/index.php?s=%@", [dataArray objectAtIndex:1]];
NSURL *url = [[NSURL alloc] initWithString:myURL];
NSString *strResult = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
// display dataArray sent from Main Thread ... AGAIN
NSLog(@"this will show");
NSLog(@"%i, %@", [[dataArray objectAtIndex:0] intValue], [dataArray objectAtIndex:1]);
NSLog(@"this will not show");
// Code that returns super cool data to the main thread
[pool release]; // empty pool
I’m not 100% sure that data does corrupt but I don’t understand why does the same line of code (NSLog) crash the app. I have to use data from my dataArray after the Fetch from URL but can’t.
I’m new to Objective C so I’m sorry if my error is obvious 🙂
— UPDATE — object sent to this method wasn’t retained and that was the problem!
How do you create and manage the array sent to the background thread?
If you have a crash, post the backtrace.
Your workaround isn’t a fix, it is just narrowing the window of whatever race condition is killing your app.
Best guess (lacking the code showing how the array is created) is that your array is being released by the main thread before the background thread is done with the array and strings.
Retain the array once for each thread that is spawned and then release it in the thread when you are done with it.
Better yet, use GCD + Blocks.