Re: NSOperationQueue and for-loop
Re: NSOperationQueue and for-loop
- Subject: Re: NSOperationQueue and for-loop
- From: Mike Abdullah <email@hidden>
- Date: Wed, 03 Oct 2012 13:48:29 +0100
On 3 Oct 2012, at 13:37, Koen van der Drift <email@hidden> wrote:
> On Tue, Oct 2, 2012 at 10:30 PM, Koen van der Drift
> <email@hidden> wrote:
>
>>> Thanks, I'll Google for some examples. For now, I still get an EXC_BAD_ACCESS (code=13, address = 0x0) error in one of the threads after several iterations. Some more digging reveals:*** -[MyObject setPosition:]: message sent to deallocated instance 0x1075a6480. This address is the current MyObject, and only one is created during each iteration.
>>
>> It's all very confusing still. I'll keep looking.
>
>
> I'm not at my Mac right now (I have a non-programming daytime job),
> but I think I know what could be going on. This is some code (typed in
> email program) very similar to what I did so far and which was causing
> the crashes:
>
> NSUInteger __block i, j,;
> MyObject __block *newObj;
>
> NSMutabbleArray *temp = [[NSMutableArray alloc] init];
> NSOperationQueue *q = [[NSOperationQueue alloc] init];
>
> for (i = 0; i < 10; i++) {
> [q addOperationWithBlock: ^{
> for (j=1; j < 5; j++) {
> newObj = [MyObject alloc] init];
> [newObj doSomething: i];
> [newObj doSomethingElse: j];
>
> [temp addObject: newObj];
> }
> }];
> }
>
> [q waitUntilAllOperationsAreFinished];
> [self updateUIWithArray: temp];
>
> The crash would always occur at one of the doSomething calls, and is
> related to newObj already being dellocated ("message sent to
> deallocated instance"). So maybe with all those thread going on,
> newObj somehow gets re-used before it was added to temp.
>
> So I see two solutions: 1) add a copy of newObj to temp, or 2) put
> the declaration of newObj inside the inner for loop.
>
> I won't be able to test it until later, but am I on the right track here?
>
> Also, is waitUntilAllOperationsAreFinished needed to make sure all
> iterations are completed before moving on to update the UI?
Regardless, your posted code is going to blow up sooner or later. NSMutableArray is not safe to modify from more than a single thread at a time. If two of your worker blocks happen to finish at the same time and call -addObject: together, nasty things will happen.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden