在我的项目中,我在具有相同 MOC 和 Persistence Store 的同一数据模型中的两个不同实体中输入相同的对象。我不想复制实体,因为我要从第一个实体中修改(删除)对象。我的问题是我将如何从另一个实体中获取对象?我需要有不同的持久性存储和 MOC 吗?好吧,我已经获取了对象,但它给了我空值并崩溃告诉该对象不能是零值。
我猜价值没有保存在核心数据中。以下是我用来将值存储在 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);
}