核心数据获取最初不是“故障”,而是变成“故障”

时间:2012-08-31 02:44:05

标签: ios core-data fault

我有一个具有此方法的单例数据管理器:

-(NSArray*)fetchItems
{
NSEntityDescription *entity = [NSEntityDescription
                               entityForName:@"Item" inManagedObjectContext:self.managedObjectContext];


NSError *error2;
NSFetchRequest *itemFetchRequest = [[NSFetchRequest alloc] init];
[itemFetchRequest setEntity:entity];
[itemFetchRequest setReturnsObjectsAsFaults:NO];


NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"order"
                                                               ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[itemFetchRequest setSortDescriptors:sortDescriptors];

NSArray *fetchedItems = [self.managedObjectContext executeFetchRequest:itemFetchRequest error:&error2];


return fetchedItems;


}

然后我根据核心数据对象创建一些视图,如下所示:

self.items = [dataManager fetchItems];
for (Item *item in self.items) { //Item is the NSManagedObject subclass
    ItemView *itemView = [[ItemView alloc] initWithFrame:aFrame ];

    [itemView layoutWithData:item];
    [self.someView addSubview:itemView];

}

ItemView的数据设置如下:

- (void)layoutWithData:(Item*)_data {
self.data = _data;

NSLog(@"ItemView data: %@", self.data); //not "fault" at this point
...

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:data.image forState:UIControlStateNormal];
[btn addTarget:self action:@selector(tapDetected:) forControlEvents:UIControlEventTouchUpInside];
btn.frame = aFrame;
[self addSubview:btn];

}

此时,ItemView的数据已定义且不是“错误”。但是,当检测到这样的点击时:

- (void)tapDetected:(id)sender
{
NSLog(@"TAP: %@", self.data); //fault - see below
[self.delegate itemTapped:self.data];
}

我得到这样的东西:

TAP: <Item: 0x879ce40> (entity: Item; id: 0x8798310 <x-coredata://8BE9ABFE-7C63-4ADD-9AD1-62B81C5AFF66/Item/p66> ; data: <fault>)

当我点击ItemView时,为什么数据首先是“非故障”然后是“故障”,我该如何解决?这一整天都在扼杀我......

编辑:使用此代码,我可以确认数据不是layoutWithData方法中的错误,但是在tapDetected方法中是错误的:

NSLog(@"is fault? %i", self.data.isFault);

为什么会变成错误???

1 个答案:

答案 0 :(得分:0)

这可能不是一个问题,但是一个错误意味着尚未读取数据。在获取前尝试执行以下操作:

[fetchRequest setReturnsObjectsAsFaults:NO];

这样就可以完全读取数据了。

请参阅 Similar Question