0

I use below code in my code for fetching data from 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];

It seems that when I change my CoreData entity (deleting items) the Items array also changes? Is it correct?

If yes, how can I avoid this?

1 Answer 1

2

You need to create a wrapper class that would be instantiated using core data entity and work with objects of that class in your code.

For example, if you have such entity

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

You should create a 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

UPDATE: (duplicate comment here for better readability)

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

Than you work with newArray.

Sign up to request clarification or add additional context in comments.

1 Comment

so how use this wrapper class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.