【问题标题】:How to save data loaded from core data in array?如何将从核心数据加载的数据保存在数组中?
【发布时间】:2015-05-20 13:02:34
【问题描述】:

我在代码中使用以下代码从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 数组也发生了变化?对吗?

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

【问题讨论】:

    标签: ios core-data nsmanagedobject nsmanagedobjectcontext nsfetchrequest


    【解决方案1】:

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

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

    @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合作。

    【讨论】:

    • 那么如何使用这个包装类呢?
    猜你喜欢
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 2011-03-15
    • 2015-02-26
    • 2020-10-09
    • 2019-10-10
    相关资源
    最近更新 更多