我正在尝试将核心数据中的对象列表显示到 UITableViewController 中。这是这个 UITableViewController 的 viewWillAppear:
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
self.landmarks = [[TSDataManager sharedInstance] fetchArrayFromDBWithEntity:@"Landmark" forKey:nil withPredicate:nil];
[self.tableView reloadData];
}
这是 fetchArrayFromDBWithEntity:forKey:withPredicate: 实现:
- (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;
}
当表格首次出现时,一切都正确显示,我有 4 个从数据库返回的对象,其标题正确显示在每个单元格中。
但是每当我转到另一个视图并返回时,该表有四个对象,但它们的“标题”属性的值为 nil!
这是我的地标类的代码:
@interface Landmark : NSManagedObject
@property (nonatomic, strong) NSString * title;
@end
@implementation Landmark
@dynamic title;
@end
这是我的表格单元格的构造方式,以防它来自那里:
- (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;
}
显然我在这里做错了什么,但我真的不知道是什么。