2012-02-02 72 views
0

我只是試圖保存一個ManagedObjectContext,但是當我沒有得到任何錯誤時,獲取的請求返回沒有保存值的對象。考慮這個簡單的例子。你有一個單一的對象,你改變一個屬性並保存它。該對象在那裏,但該屬性未保存。正如你所看到的,我只想要一個對象,並且獲取返回這個對象。順便說一句,代碼是在一個簡單的類,而不是應用程序委託或視圖控制器。核心數據,無法保存上下文

下面是示例代碼:

MyAppDelegate* delegate = [[UIApplication sharedApplication] delegate]; 

NSManagedObjectContext* context = delegate.managedObjectContext; 

NSEntityDescription *myEntityDesc = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:context]; 

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; 

[request setEntity:myEntityDesc]; 

NSError *error = nil; 

NSArray *array = [context executeFetchRequest:request error:&error]; 
MyEntity* myEntity; 

if (array == nil || [array count] < 1) 
{ 
    myEntity = [NSEntityDescription insertNewObjectForEntityForName:@"MyEntity" inManagedObjectContext:context]; 
} 
else 
{ 
    myEntity = [array objectAtIndex:0]; 
} 

myEntity.BoolValue = [NSNumber numberWithBool:someBoolValue]; 
myEntity.ID = @"Some ID"; 

if ([context save:&error]) 
{ 
    NSLog(@"no error"); 
} 
else 
{ 
    NSLog([NSString stringWithFormat:@"found core data error: %@", [error localizedDescription]]); 
} 

這裏的稍後用於檢索值的代碼:

MyAppDelegate* delegate = [[UIApplication sharedApplication] delegate]; 

NSManagedObjectContext* context = delegate.managedObjectContext; 

NSEntityDescription *MyEntityDesc = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:context]; 

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; 

[request setEntity:MyEntityDesc]; 

NSError *error = nil; 

NSArray *array = [context executeFetchRequest:request error:&error]; 

MyEntity* myEntity; 

if (array == nil || [array count] < 1) 
{ 
    //handle error 
} 
else 
{ 
    myEntity = [array objectAtIndex:0]; 
} 

return [myEntity.BoolValue boolValue]; 
+1

你可以驗證你的託管對象上下文不是'nil'嗎? – sho 2012-02-02 16:29:58

+0

我把檢查到處都是。對象仍在範圍內。 – CYAD 2012-02-03 03:33:19

回答

0

什麼是您的NSManagedObject子類是什麼樣子?由於提取工作正常(即返回實體),我懷疑子類實現中有什麼錯誤。

您應該爲數據模型中的每個屬性聲明@property。並且在實現文件中,而不是使用@synthesize,您需要使用@dynamic。還請確保您的xcdatamodel實體具有其類設置以及名稱。

@interface MyEntity : NSManagedObject 
@property (nonatomic, strong) NSNumber * boolValue; 

@end 

@implementation MyEntity 
@dynamic boolValue; 

@end