神秘的核心数据行为在第二次获取时检索空对象

时间:2013-02-01 23:46:02

标签: ios objective-c core-data

我正在尝试将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: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;
}

当表格首次出现时,一切都正确显示,我有4个对象从DB回来,每个单元格中都有正确显示的标题。

但每当我去另一个视图然后回来时,该表有四个对象,但是它们的“title”属性的值是nil!

以下是我的Landmark类的代码:

@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;
}

显然我在这里做错了,但我真的不知道是什么。

1 个答案:

答案 0 :(得分:0)

事实证明,问题来自我将Core Data实现为单例。我用NLCoreData(https://github.com/jksk/NLCoreData)替换它,现在一切正常。