Mysterious core data behavior retrieves empty objects in second sample
I am trying to display a list of objects from Core Data in a UITableViewController. Here is the viewWillAppear of this UITableViewController:
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
self.landmarks = [[TSDataManager sharedInstance] fetchArrayFromDBWithEntity:@"Landmark" forKey:nil withPredicate:nil];
[self.tableView reloadData];
}
And here is fetchArrayFromDBWithEntity: forKey: withPredicate: implementation:
- (NSMutableArray*)fetchArrayFromDBWithEntity:(NSString*)entityName forKey:(NSString*)keyName withPredicate:(NSPredicate*)predicate {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
if(keyName != nil){
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:keyName ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
}
if (predicate != nil){
[request setPredicate:predicate];
}
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
NSLog(@"%@", error);
}
return mutableFetchResults;
}
When the table first appears, everything is displayed correctly, I have 4 objects returning from the DB with the titles displayed correctly in each cell.
But whenever I change to a different view and come back, the table has four objects in order, but the value of their title property is nil!
Here is the code for my Landmark class:
@interface Landmark : NSManagedObject
@property (nonatomic, strong) NSString * title;
@end
@implementation Landmark
@dynamic title;
@end
And this is how my table cells are constructed, if it happens from here:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"LandmarkCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
Landmark *landmark = (Landmark *) self.landmarks[(NSUInteger) indexPath.row];
cell.textLabel.text = landmark.title;
return cell;
}
Obviously I am doing something wrong here, but I seriously cannot figure out what.
source to share
It turned out that the problem originated from my Core Data implementation as a singleton. I replaced it with NLCoreData ( https://github.com/jksk/NLCoreData ) and now everything works fine.
source to share