简体   繁体   中英

Loading contents of an NSArray into a UITableView

I have populated an NSArray called **teacherNames*. The data successfully comes in from a Core data entity called Teachers using the following:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Teachers"];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Teachers" inManagedObjectContext:self.managedObjectContext];

request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"teacherName" ascending:YES]];
request.entity = entity;
request.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"teacherName"]];

NSError *error = nil;
self.teacherNames = [self.managedObjectContext executeFetchRequest:request error:&error];
[self.tableViewTeacherNames reloadData];

I can see that there are there as when I type the following in the debug window:

print self.teacherNames.count

it returns the correct number in the array.

However when I try to use the NSArray to populate the table using:

- (UITableViewCell *)tableView:(UITableView *)tableViewTeacherNames cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"teacherCell";
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
NSString *currentItem = [[self.teacherNames objectAtIndex:indexPath.row] objectForKey:@"teacherName"]; - ERROR LINE
cell.textLabel.text = currentItem;
return cell;
}

I get this error

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject objectForKey:]: unrecognized selector sent to instance 0xb88ce30'

Can anyone suggest what I am doing wrong?

Try using valueForKey: instead of objectForKey: . The latter belongs to NSDictionary whereas the former to any NSObject descendant

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM