核心数据,无法保存上下文

问题描述:

我只是试图保存一个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

什么是您的NSManagedObject子类是什么样子?由于提取工作正常(即返回实体),我怀疑子类实现中有什么错误。

您应该为数据模型中的每个属性声明@property。并且在实现文件中,而不是使用@synthesize,您需要使用@dynamic。还请确保您的xcdatamodel实体具有其类设置以及名称。

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

@end 

@implementation MyEntity 
@dynamic boolValue; 

@end