Core Data のオブジェクトのリストを 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;
}
テーブルが最初に表示されると、すべてが正しく表示されます。DB から 4 つのオブジェクトが返され、タイトルが各セルに正しく表示されます。
しかし、別のビューに移動して戻ってくるたびに、テーブルには 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;
}
明らかに、私はここで何か間違ったことをしていますが、真剣に何がわかりません。