核心数据对象的生命周期和编译器优化

我有这两个帮手的方法。 将Xcode中的优化级别设置设为无(debugging模式的默认设置),代码工作正常。 但是,如果“优化级别”设置为None以外的任何值,则会生成testGetAllRecords中的日志(空)。

有什么build议,为什么这样performance? 我错过了什么?

(正在使用ARC)

+(NSArray *)getAllRecords { NSError *error; CoreDataController *coreDataController = [[CoreDataController alloc]init]; NSManagedObjectContext *context = [coreDataController managedObjectContext]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Group1" inManagedObjectContext:context]; [fetchRequest setEntity:entity]; NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]; NSArray *sortDescriptors = [NSArray arrayWithObjects:sortByName, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; for (Group1 *aGroup in fetchedObjects) { // This produces valid data NSLog(@"getAllRecords name:%@", aGroup.name); } NSLog(@"getAllRecords currenthread: %@", [NSThread currentThread]); //shown thread num = 1 return fetchedObjects; } +(void)testGetAllRecords { NSLog(@"testGetAllRecords currenthread: %@", [NSThread currentThread]); //shown thread num = 1 NSArray *allRecords = [DataStoreInterfaceWrapper getAllRecords]; for (Group1 *aGroup in allRecords) { //This produces "(null)" when Xcode Optimization Level not set to None NSLog(@"testGetAllRecords name:%@", aGroup.name); } } 

在函数中使用临时上下文的事实意味着它在该函数结束时被释放,孤立所有与之连接的被pipe理对象(将它们转换为无上下文的错误)。

随着你的优化,当你的上下文不再被保留(在函数结束时),而没有优化和“debugging”模式时,这个对象不会立即被释放。

使用保留的上下文(一个超过function的范围),一切都应该没问题。