在我的项目中,我在具有相同MOC和持久性存储的相同数据模型中的两个不同实体中输入相同的对象。我不想复制实体,因为我要从第一个实体修改(删除)对象。我的问题是我将如何从另一个实体获取对象?我需要拥有不同的持久性存储和MOC吗?好吧,我已经获取了对象但是它给了我null值并且崩溃告诉对象不能是零值。
我猜数值不会保存在核心数据中。以下是我用于存储coreData
中的值的代码行CommonEvent *commonEvent = (CommonEvent *)[NSEntityDescription insertNewObjectForEntityForName:@"CommonEvent" inManagedObjectContext:_managedObjectContext];
[commonEvent setValue:number forKey:@"commonNumber"];
[commonEvent setValue:name forKey:@"commonName"];
以下是从核心数据中获取数据的代码行
CommonEvent *event;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"CommonEvent" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// define a sort descriptor
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc]initWithKey:@"commonName" ascending:YES];
NSSortDescriptor *numberDescriptor = [[NSSortDescriptor alloc]initWithKey:@"commonNumber" ascending:YES];
NSArray *scArray = [[NSArray alloc]initWithObjects:nameDescriptor,numberDescriptor, nil];
// give sort descriptor array to the fetch request
fetchRequest.sortDescriptors = scArray;
// fetch all objects
NSError *error = nil;
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
NSLog(@" we have a problem: %@", error);
}
NSMutableArray *mutableArray = [[NSMutableArray alloc]init];
NSLog(@" %@ %@ for index:%d", [event.commonNumber description],[event.commonName description], indexPath.row); // It shows that object values are null
// display all objects
for (CommonEvent *event in fetchedObjects) {
[mutableArray addObject:[event.commonNumber description]];
//
NSLog(@" %@ %@ for index:%d", [event.commonNumber description],[event.commonName description], indexPath.row);
}
答案 0 :(得分:1)
您必须在将数据插入MOC后保存数据:
NSError *error;
[_managedObjectContext save:&error];
另外,为什么在创建NSManagedObject子类时使用键值编码?您可以使用点表示法编写并避免错误:
commonEvent.commonNumber = number;
commonEvent.commonName = name;
此外,在您的代码中,您声明event
并且从不对其进行初始化。当然会是nil
。您可能打算使用提取的结果,例如
CommonEvent *event = fetchedObjects.count ? fetchedObjects[0] : nil;
如果您使代码更简洁,您的代码将更容易阅读:
NSFetchRequest *request =
[NSFetchRequest fetchRequestWithEntityName:@"CommonEvent"];
request.sortDescriptors = @[
[NSSortDescriptor sortDescriptorWithKey:@"commonName" ascending:YES],
[NSSortDescriptor sortDescriptorWithKey:@"commonNumber" ascending:YES]];
NSError *error;
NSArray *fetchedObjects = [_managedObjectContext executeFetchRequest:request
error:&error];