2013-04-05 46 views
1

我遇到了一個問題,我有一個方法應該返回從當前線程的上下文中獲取的Core Data實體對象。核心數據實體在方法返回後缺少其屬性

當我在DEBUG模式下編譯並運行項目時,所有工作都很好,但是當應用程序作爲RELEASE運行時會出現一個奇怪的行爲。返回的對象缺少它的屬性(它們是零或0)。該應用程序正在使用ARC來管理內存。

實施有效利用上NSManagedObject類別有這樣的梅託德:

- (id)threadLocalSelf { 
    return [self selfInContext:[NSManagedObjectContext threadLocalContext]]; 
} 

- (id)selfInContext:(NSManagedObjectContext *)context { 
    NSAssert(context, @"context cannot be nil!"); 
    if(context == self.managedObjectContext) 
     return self; 

    NSManagedObjectID *objectID = [self objectID]; 
    if([objectID isTemporaryID]) 
     [NSException raise:NSInternalInconsistencyException format:@"objectID cannot be temporary when fetching self in another context!"]; 

    NSError *error = nil; 
    NSManagedObject *_self = [context existingObjectWithID:objectID error:&error]; 
    if(error) 
     [NSException raise:NSInternalInconsistencyException format:@"Failed to fetch self: %@ in context: %@, error: %@", objectID, context, error]; 

    NSAssert(_self, @"context: %@ does not contain an object with objectID: %@", context, objectID); 

    NSLog(@"Returning _self: %@", _self); 

    return _self; 
} 

[NSManaged threadLocalContext]當前線程創建一個新的NSManagedObjectContext。

這裏的問題是,當NSLogging出即將返回的對象似乎很好。關於實體的所有屬性和信息都是正確的。

但是,在退出對象之後(如下所示),所有屬性都是零或0.此行爲只發生在RELEASE中,而不是DEBUG。

Foo * bar = [baz threadLocalSelf]; 
NSLog(@"Foo object: %@", bar); 

上面的代碼導致從該方法內正確註銷對象,但NSLog之後的屬性爲空。雖然ObjectID在兩種情況下都是正確的,並且對象本身不是零。

對什麼可能會導致此問題的任何想法都非常appriciated。

回答

2

你的線程新上下文在被分配和使用後被釋放。

- (id)threadLocalSelf { 
    return [self selfInContext:[NSManagedObjectContext threadLocalContext]/*released at the end of method*/]; 
} 
+0

Thanks!你剛剛救了我的一天。 – oehman 2013-04-05 15:08:36

+0

沒問題,很高興幫助:) – 2013-04-05 15:09:48

1

你看到此行爲僅在發佈版本是因爲NSManagedObjectContext被放入自動釋放池在調試版本的原因,但ARC優化器會立即在發佈版本釋放它。您可以在調試版本中通過使自動釋放池立即消失來複制此內容:

- (id)threadLocalSelf { 
    @autoreleasepool { 
     return [self selfInContext:[NSManagedObjectContext threadLocalContext]]; 
    } 
} 
+0

感謝您解釋DEBUG/RELEASE區別! – oehman 2013-04-05 15:14:25