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];
你可以驗證你的託管對象上下文不是'nil'嗎? – sho 2012-02-02 16:29:58
我把檢查到處都是。對象仍在範圍內。 – CYAD 2012-02-03 03:33:19