我在使用后台线程上的批量更新更新到核心数据时遇到了问题。在下面的代码中,我使用主线程通知用户进度视图和调用appdelegate中方法的字符串。但是如果我在随机数量的数据中的NSEntity行中出现错误的访问错误,我有数千个对象需要更新。如果我取消注释我在下面指出的NSLOG没有错误,或者如果我评论主线程没有错误,或者,如果我不批量更新,如果我使用批量更新,那么也没有错误。如果我评论自动释放池也出现错误。请问有些人帮我解决这个问题。
提前致谢,
干杯, Shravan
NSAutoreleasePool *tempPool = [[NSAutoreleasePool alloc] init];
NSUInteger iterator = 1;
for (int i = 0; i < totalNo; i++) {
NSDictionary *alertResult = [[alertResultList objectAtIndex:i] retain];
if (alertResult == nil) {
continue;
}
//managedObjectContext = [appDelegate.managedObjectContext retain];
NSLog(@"Object Count:%u", [[managedObjectContext insertedObjects]count]);
AlertResult *result = (AlertResult *)[NSEntityDescription
insertNewObjectForEntityForName:@"AlertResult"
inManagedObjectContext:managedObjectContext];
[result setUserName:@"A"];
iterator++;
//When count reaches max update count we are saving and draining the pool and resetting the pool
if (iterator == kUploadCount) {
if ([self update] == NO) {
// If unable to update Alert results in the Core Data repository, return
// a custom status code.
statusCode = -1;
}
[managedObjectContext reset];
[tempPool drain];
tempPool = [[NSAutoreleasePool alloc] init];
iterator = 0;
}
//Adding code to change the display string for the lock view to notify user
float count1 = (float)(counter/totalAlerts);
counter = counter + 1.0f;
NSString *dispStr = [NSString stringWithFormat:@"%f",count1];//[NSString stringWithFormat:@"Loading %d out of %d alerts",(i+1),totalAlerts];
NSString *dispMess = [NSString stringWithFormat:@"Alerts %d of %d",(i+1),totalNo];
[self performSelectorOnMainThread:@selector(changeLockScreenMessageWith:) withObject:[NSArray arrayWithObjects:dispStr,dispMess, nil] waitUntilDone:YES];
//NSLog(@"count"); /* If I uncomment this line code runs fine */
[alertResult release];
alertResult = nil;
}
//If count is inbetween the update limit we are updating and we are draining the pool
if (iterator != 0) {
if ([self update] == NO) {
// If unable to update Alert results in the Core Data repository, return
// a custom status code.
statusCode = -1;
}
[managedObjectContext reset];
//[tempPool drain];
}
//Out side the previous method
- (BOOL)update {
NSError *error;
if (![managedObjectContext save:&error]) {
NSLog(@"%@", [error userInfo]);
return NO;
}
return YES;
}
答案 0 :(得分:1)
您所描述的崩溃类型的最可能原因是跨线程使用managedObjectContext
。 managedObjectContext
不是线程安全的。您必须为每个线程创建一个新的MOC。我认为managedObjectContext
是一个伊娃;你永远不应该像这样直接访问你的ivars(init和dealloc除外)。始终使用访问器为您处理内存管理。
NSLog
导致崩溃的原因是NSLog
显着改变了此功能的时间,并且您有竞争条件。