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

How to save data loaded from core data in array?

我在代码中使用以下代码从 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 数组也会更改?正确吗?

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

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

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

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

您应该创建一个 class

@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 一起工作。