-1

在我的项目中,我在具有相同 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);
}
4

1 回答 1

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];
于 2013-07-15T18:38:05.363 回答