核心数据对象的生命周期和编译器优化 [英] Life cycle of core data objects and compiler optimization

查看:273
本文介绍了核心数据对象的生命周期和编译器优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这两个帮助方法。将Xcode中的优化级别设置为无(调试模式为默认值),代码可以正常工作。但是如果优化级别设置为None之外的任何其他,testGetAllRecords中的日志(null)。

I have these two helper methods. With the Optimization Level settings in Xcode to None (default for debug mode), the codes work fine. But if the Optimization Level is set to anythings other than None, the logs in the testGetAllRecords produced (null).

任何建议为什么它的行为这样?

Any suggestions why it behaves this way? Did I miss something?

(正在使用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);
    }
}


推荐答案

事实上,您在函数中使用临时上下文意味着它在此函数结束时释放,孤立所有与其连接的管理对象(将其转换为具有nil上下文的故障)。

The fact that you use a temporary context inside a function mean that it is released at the end of this function, orphaning all managed objects connected to it (turning them to faults with nil context).

根据你的优化,当你的上下文不再保留(在函数的结尾)时,这会立即发生,而没有优化和在调试模式,你的对象不会立即释放

With your optimisations on, this happen immediately when your context is no longer retained (at the end of the function), while without optimisations and in "debug" mode, you objects are not released as soon as they are no longer needed.

使用保留的上下文(超过函数范围的上下文),所有内容都应该很好。

Use a retained context (one that outlive the scope of the function) and all should be fine.

这篇关于核心数据对象的生命周期和编译器优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆