简单 iOS 核心数据查询

Simple iOS Core Data Query

我正在尝试从核心数据中提取记录。我可以成功地这样做,但我在尝试将查询的元素放在 UITableView 中时总是收到以下错误。如果您需要更多信息,请告诉我。我认为问题是我没有使用正确类型的数据结构来填充提要。

错误:

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

valueForKey 如您所写,它将 return 项目中每个对象的所有 item_name 字段的数组。这就是为什么您的错误是“[__NSArrayI isEqualToString:]”。

您可能想要做的是

Item *cellData = (Item *)items[indexPath.row];
cell.textLabel.text = cellData.item_name;

您的 FetchRequest returns 您是一个 "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 将具有 class Item

的对象