在将我的应用程序发送到应用程序商店之前,我喜欢使用工具检查它是否存在内存泄漏和其他可疑内容。有一个核心数据问题我似乎无法解决,因此我决定创建一个小型测试应用程序来说明该问题。
有什么问题?
当我将实体保存在(子)NSManagedObjectContext 中时,它会传播到其父 NSManagedObjectContext。在此过程中,Core Data 创建了以下对象的内部实例:_NSObjectID
and NSTemporaryObjectID
。由于某种原因,这些实例被留下,摆脱它们的唯一方法是重置父 NSManagedObjectContext。
我的应用程序当然比这个小测试应用程序复杂得多,并且重置 NSManagedObjectContext 对我来说不是一个选择。
Test app
测试应用程序是一个基于单视图模板的标准 iOS 应用程序,并选中了 CoreData 选项。我使用 Objective-C 来使其与我的生产应用程序相似。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Initialize the Core Data stack
self.persistentStoreCoordinator = [self persistentStoreCoordinator];
// Create the a private context
self.rootContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
self.rootContext.persistentStoreCoordinator = self.persistentStoreCoordinator;
// Create a child context
self.childContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
self.childContext.parentContext = self.rootContext;
// Create a person
[self.childContext performBlockAndWait:^{
Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.childContext];
person.name = @"John Smith";
person.age = 30;
// Save the person
[self.childContext save:nil];
// Save the root context
[self.rootContext performBlockAndWait:^{
[self.rootContext save:nil];
}];
}];
return YES;
}
当您使用工具和分配工具运行上面的代码时,您可以看到核心数据留下了一些东西。
您可以在这里找到完整的项目:https://github.com/Zyphrax/CoreDataLeak https://github.com/Zyphrax/CoreDataLeak
我尝试过的事情
我尝试过类似的事情[context refreshObject:... mergeChanges:YES]
,添加@autoreleasepool
and/or [context processPendingChanges]
在街区内,这一切都没有帮助。让它干净的唯一方法是做一个[context reset]
(大锤方法)。
很难找到其他人报告此问题。
这篇博文看起来很相似:
http://finalize.com/2013/01/04/core-data-issues-with-memory-allocation/ http://finalize.com/2013/01/04/core-data-issues-with-memory-allocation/
我希望你们能帮我解决这个问题。