如何保存从数组中的核心数据加载的数据?

时间:2015-05-20 13:02:34

标签: ios core-data nsmanagedobject nsmanagedobjectcontext nsfetchrequest

我在代码中使用以下代码从CoreData获取数据:

id appdelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *managedObjectContext = [appdelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"TelePayment" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"index" ascending:YES];
[fetchRequest setSortDescriptors:@[sort]];
NSError *error = nil;
 Items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

似乎当我更改CoreData实体(删除项目)时,Items数组也会发生变化?这是对的吗?

如果是,我该如何避免这种情况?

1 个答案:

答案 0 :(得分:2)

您需要创建一个包装类,该类将使用核心数据实体进行实例化,并在您的代码中使用该类的对象。

例如,如果您有这样的实体

@interface Item: NSManagedObject
  NSInteger id;
  NSString *name;
@end

你应该创建一个类

@interface ItemObject: NSObject
  NSInteger itemId;
  NSString *itemName;
@end

@implementation ItemObject

  - (void)initWithEntity:(NSManagedObject*)entity {
    self = [super init];
    if (self) {
      _itemId = entity.id;
      _itemName = entity.name;
    }
    return self;
  }
@end

更新 :(此处重复评论以提高可读性)

...
Items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSMutableArray *newArray = [NSMutableArray new];
for (NSManagedObject *object in items) {
  ItemObject *newItem = [[ItemObject alloc] initWithEntity:object];
  [newArray addObject:newItem];
}

比使用newArray