我试图从Core Data中提取记录。我可以成功地这样做,减去在尝试将查询的元素放在UITableView中时总是收到以下错误的事实。如果您需要更多信息,请与我们联系。我认为问题在于我没有使用适当类型的数据结构来填充Feed。
错误:
<NSManagedObject: 0x7ff4cb712f10> (entity: Item; id: 0xd000000000040000 <x-coredata://B5B03BED-0A3E-45EA-BC52-92FB77BE0D51/Item/p1> ; data: <fault>)
2015-04-05 20:29:17.080 TacticalBox[99411:6444447] -[__NSArrayI isEqualToString:]: unrecognized selector sent to instance 0x7ff4cb71a760
2015-04-05 20:29:17.114 TacticalBox[99411:6444447] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI isEqualToString:]: unrecognized selector sent to instance 0x7ff4cb71a760'
代码:
@property (strong, nonatomic) NSArray *items;
- (void)viewDidLoad {
[super viewDidLoad];
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
// Do any additional setup after loading the view.
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
NSError *error;
items = [context executeFetchRequest:request error:&error];
for(id obj in items)
{
NSLog(@"%@",obj);
}
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = [items valueForKey:@"item_name"];
return cell;
}
答案 0 :(得分:0)
valueForKey在您编写时将返回项目中每个对象的所有item_name字段的数组。这就是为什么你的错误是“[__NSArrayI isEqualToString:]”。
您可能想做的事情就像是
Item *cellData = (Item *)items[indexPath.row];
cell.textLabel.text = cellData.item_name;
答案 1 :(得分:0)
您的FetchRequest会返回一个“Item”对象数组,这些对象存储在您集合的每个索引处。
访问这些对象时,您应首先从相应的索引中获取项目,例如
Item* anItem = [items objectAtIndex:indexPath.row];
接着是
cell.textLabel.text = [anItem valueForKey:@"item_name"];
其中item_name在anItem
对象上声明属性。
作为安全检查,您也可以使用 -
id anItem = [items objectAtIndex:indexPath.row];
if ([anItem isKIndOfClass:[Item class]]) {
cell.textLabel.text = [(Item*)anItem valueForKey:@"item_name"];
}
但这绝对是多余的,因为您的FetchQuery明确指定您的items
将包含类Item
的对象