开发者

Debugging NSOperationQueue Blocking

I need some guidance in how to debug problems with concurrency in Cocoa under 10.6. I'm converting a 'for' loop to use NSOperations but most of the time, the code just freezes at some point through the loop. I can see NSLog output in the console to that effect. On the rare occasion, the code will run all the way through and it's fine.

The code is model-layer only, initiated from a method in the controller. The method loops through just 8-10 model objects, instructing them to each write their output to a uniquely named file. 8 model objects = 8 separate files. There are no calls up to the GUI and the model objects are NSManagedObject subclasses, which contain a set of child NSManagedObject objects (0..n of them), which each owning object summarizes and writes out. The output format is JSON.

Code:

__block NSMutable开发者_开发问答Array *collectionOfCourses = [[NSMutableArray alloc] initWithCapacity:[[self courses] count]];

/* Create a filename.  Use our title and set it to lowercase */
NSURL *ourFileURL = [aURL URLByAppendingPathComponent:[[self title] lowercaseString]];
ourFileURL = [ourFileURL URLByAppendingPathExtension:@"js"];

for (Course *aCourse in [self courses]) {
       [[self opQueue] addOperationWithBlock:^{
       NSArray *arrayForOneCourse = [aCourse arrayAndWriteToFileURL:aURL fileFormat:format];
   [collectionOfCourses addObject:arrayForOneCourse];
    }];
}

I do a lot of NSLogs, would that be the issue? Is NSLog'ing from background threads a bad thing?

Since I'm adding to the mutable array from withinside a block, is it correct that I declare the mutable array as __block? I've tried it both ways and seemingly no difference relating to this freezing problem.

How do I debug this problem using Xcode v4? I want to know the line of code that it's freezing on, or what two lines of code are executing at the same time and causing it to block the execution.. My former techniques of setting a single breakpoint and stepping through the code no longer work, because of the concurrency.

thanks


It's nothing to do with your block-scoped variable. Your problem is that neither NSMutableArray nor NSManagedObject are in any way, shape or form thread-safe. You cannot do what you're doing here. If you want to have this processed off the main thread, you need to use a dispatch queue or something similar to process each item serially (and even when you're back on the main thread, you should use that same queue before you read from your mutable array. It'd probably be easier and safer, however, to do something like copy the mutable array to an immutable version when you're finished and then dispatch a notification or call-back to the main thread with the new, immutable copy embedded.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜