我有一个具有此方法的单例数据管理器:
-(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);
为什么会变成故障???