我的 iOS 应用程序出现异常错误。
我的应用程序会下载大量 JSON 对象,然后将这些对象插入 Core Data。每次下载都需要以下步骤:
- 打开网络连接并获取 JSON 对象
- 创建了一个主要的 NSManagedObject
- 创建 0 到大约 20 个额外的 NSManagedObjects 之间的任何数字
- 对于某些人来说,执行对现有 NAManagedObjects 的获取请求以查找现有匹配对象,并创建关系,或者如果未找到则创建新对象。
这是相关的代码片段,其中song
是 NSManagedObject 子类的实例,并且Category
是不同的 NSManagedObject 子类:
for (NSString *category in dict[@"categories"]) {
NSError *error;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Category"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name like %@", category];
NSArray *fetchResults = [_moc executeFetchRequest:fetchRequest error:&error];
Category *c;
if (fetchResults.count > 0) {
c = fetchResults[0];
} else {
c = [NSEntityDescription insertNewObjectForEntityForName:@"Category" inManagedObjectContext:_moc];
c.name = category;
}
[song addCategoriesObject:c];
}
这工作正常,直到数百次下载和插入后,应用程序才会崩溃。成功下载的数量会有所不同,似乎是随机的。
导致异常的行是NSArray *fetchResults = [_moc executeFetchRequest:fetchRequest error:&error];
,日志输出是这一行:
2014-11-17 10:05:54.265 MyApp[3211:1774124] Communications error: <OS_xpc_error: <error: 0x19ce62a80> { count = 1, contents =
"XPCErrorDescription" => <string: 0x19ce62e78> { length = 22, contents = "Connection interrupted" }
}>
2014-11-17 10:06:03.631 MyApp[3211:1773135] *** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSCFSet: 0x174075ac0> was mutated while being enumerated.'
*** First throw call stack:
(0x188111e48 0x198b140e4 0x1881117fc 0x187dc9cf8 0x1000965d8 0x100097de0 0x1003a4e30 0x1003a4df0 0x1003af854 0x1003a8120 0x1003b175c 0x1003b2f18 0x1993352e4 0x199334fa8)
libc++abi.dylib: terminating with uncaught exception of type NSException
我尝试谷歌这个错误被证明是徒劳的。(说真的 - 我从来没有搜索过错误并且得到零结果:)
有没有其他人遇到过类似的错误并且可以指出我正确的方向?这一次我完全不知道从哪里开始我的搜索。