Reputation: 5462
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?
Upvotes: 0
Views: 87
Reputation: 1317
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
.
Upvotes: 2