Walter A. Jablonowski
Walter A. Jablonowski

Reputation: 349

EXC_BAD_ACCESS while adding data to array, using 2 NSOperations simultaneously

I have:

1) Starting 2 asynchron NSUrlRequests simultaneously

2) As soon as one of the two requests has loaded XML data, an NSOperationQueue is used to start a XML parser. Hereby, the ParseOperations work excatly as in Apple's LazyTableImages example.

InfoRequestHelper.m

// ...

case GetBlogEntries:
{
    BlogParseOperation *parser = [[BlogParseOperation alloc] initWithXMLString:result delegate:self];
    parser.tag = helper.requestTag;

    [queue addOperation:parser]; // this will start the "ParseOperation"

    [parser release];

    break;
}
case GetTweets:
{
    TwitterParseOperation *parser = [[TwitterParseOperation alloc] initWithXMLString:result delegate:self];
    parser.tag = helper.requestTag;

    [queue addOperation:parser]; // this will start the "ParseOperation"

    [parser release];

    break;
}

// ...

3) When parsing is finished parser:didFinishParsing: fires.

InfoRequestHelper.m

- (void)parser:(ParseOperationBase *)parser didFinishParsing:(NSArray *)entries
{
    // Save data, remove completed request from list
    [self.requestsInProgress removeObjectForKey:parser.tag];
    [self.resultObjects addObjectsFromArray:entries];  // <= !!! EXC_BAD_ACCESS !!! here

    // ..    
}

The problem: When the first event arrives here, objects can be added to the array. But when the second arrives, there is an EXC_BAD_ACCESS.

Upvotes: 2

Views: 411

Answers (2)

Robin
Robin

Reputation: 10011

Edit: I think you are trying to access the resultObjects variable in both the parsing methods. and resultObjects is a mutableArray. so the problem is when you are trying to add or remove an object from your variable from one function another function is also trying to access it. That will give you an Error. I have learned that too when creating a multi-threaded app.

You can see the apple documentation on thread unsafe classes. and the best way to avoid it is to use a NSArray object instead.

And when you want to add or remove an object from your variable you can first put the contents into a mutable Array and do the manipulation on it and then assign it back to the original object.

I hope this makes sense. I know how hard it would have been to find such errors.

Upvotes: 1

Madhup Singh Yadav
Madhup Singh Yadav

Reputation: 8114

If you are using the same array for data fill up, then I think you are missing a basic threading concept. You must not access variable in write-mode from more than one threads.

You should first acquire a lock on the array and then proceed.

Upvotes: 0

Related Questions