所以,我有一个Core数据对象,让我们称之为会话(好吧,这就是它实际上被称为),它有四个属性(Name,Driver,Track和Car),我想在表格视图。我之前已经开始工作,但是,唉,我正在尝试使我的视图控制器更通用和可重用,所以,我正在改变它。 Anywho,这是表格的样子......
传递给视图控制器的是一个Session,它是CoreData为我提供的NSManagedObject的子类。 Driver,Car和Track都是对象关系,而name只是一个字符串。 Driver,Car和Track都有一个我在这个表中显示的name属性。我想要一种快速而肮脏的方式将此文本显示在表格中。所以,我做的就是......
NSDictionary *parameterValues = [[NSDictionary alloc] initWithObjectsAndKeys: sessionName, [NSNumber numberWithInt: 0], sessionDriver, [NSNumber numberWithInt: 1], sessionCar, [NSNumber numberWithInt: 2], sessionTrack, [NSNumber numberWithInt: 3], nil];
NSString *parameterString;
if([indexPath row] > 0) {
if([parameterValues objectForKey: [NSNumber numberWithInt: [indexPath row]]] == [NSNull null]) {
parameterString = [[NSString alloc] initWithFormat: @"Select a %@", [parameterNames objectAtIndex: [indexPath row]]];
} else{
parameterString = [[parameterValues objectForKey: [NSNumber numberWithInt: [indexPath row]]] name];
}
} else{
parameterString = [parameterValues objectForKey: [NSNumber numberWithInt: 0]];
if([parameterString isEqualToString: @""]) {
parameterString = @"Enter A Name";
}
}
这在我开始将会话作为实例变量传递之前有效,而不是跟踪特定的字符串,驱动程序,汽车和轨道对象。由于[[self session] driver]在传递新会话对象时返回nil,因此无法使用字典对象。这就是我现在这样做的方式......
//these come in handy, they're the object names (We can use KVC), and we can use them in the table titles
NSArray *parameterNames = [[NSArray alloc] initWithObjects: @"Name", @"Driver", @"Car", @"Track", nil];
//get the object for this row... (Name, Driver, Car, Track), and create a string to hold it's value..
id object = [session valueForKey: [parameterNames objectAtIndex: [indexPath row]]];
NSString *parameterValue;
NSLog(@"%@", [session name]);
//if this isn't the name row...
if(object != nil) {
//if the indexPath is greater than 0, object is not name (NSString)
if([indexPath row] > 0) {
parameterValue = [object name];
} else{
parameterValue = object;
}
} else{
//object doesn't exist yet... placeholder!
parameterValue = [@"Select a " stringByAppendingString: (NSString *)[parameterNames objectAtIndex: [indexPath row]]];
}
我要问的是......我这样做了吗?
谢谢, Matt - 核心数据新手:/
答案 0 :(得分:0)
你在想这个。如果您有这样的会话实体:
Session{
name:string
driver<-->Driver
car<-->Car
track<-->Track
}
并且Driver,Car和Track都具有name
属性,那么填写固定表所需要做的就是询问属性值,如下所示:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell=//... get cell however you do it
switch (indexPath.row) {
case 0:
cell.textLabel.text=self.currentSession.name
break;
case 1:
cell.textLabel.text=self.currentSession.driver.name;
break;
//... and so on
default:
break;
}
//... return the cell.
}
同样,要使对象传递到详细视图,您只需使用相同的switch语句来获取与所选行关联的对象。