Objective c 在UITableView中显示键值对的正确方法

Objective c 在UITableView中显示键值对的正确方法,objective-c,ios,uitableview,key-value,Objective C,Ios,Uitableview,Key Value,我有一张桌子。可能对于带有UITableViewCellStyle1的单元格,这并不重要 此外,我还有一个要显示的项目列表,供快速查看,如下所示: Gender — Male Age — 18 Height — 175 cm 对于不同的数据集,依此类推。可能是一个具有属性的类Human,GenderType-gender,NSInteger-age,float-height。我希望它能像上面那样表现出来。此外,这种方法应该是灵活的,我想以我的方式快速而清晰地重新排列这些值。不使用CoreDat

我有一张桌子。可能对于带有
UITableViewCellStyle1
的单元格,这并不重要

此外,我还有一个要显示的项目列表,供快速查看,如下所示:

Gender — Male
Age — 18
Height — 175 cm
对于不同的数据集,依此类推。可能是一个具有属性的类
Human
GenderType-gender
NSInteger-age
float-height
。我希望它能像上面那样表现出来。此外,这种方法应该是灵活的,我想以我的方式快速而清晰地重新排列这些值。不使用CoreData

第一个快速解决方案是制作两个字典,并将它们链接到DB中:

NSDictionary*keys=@{@0:@“性别”、@1:@“年龄”、@2:@“身高”};
NSDictionary*值=@{@0:@“男性”、@1:@18、@2:@“175厘米”};
NSArray*source=@[@0、@1、@2];//我点的菜

现在我开始使用属性如下的
Pair

@property(非原子,强)NSString*键;
@属性(非原子,强)id值;
-(id)initWithKey:(NSString*)键值:(id)值;
现在代码看起来像

Pair*genderPair=[[Pair alloc]initWithKey:@“性别”值:@“男性”];
Pair*agePair=[[Pair alloc]initWithKey:@“Age”值:@18];
Pair*heightPair=[[Pair alloc]initWithKey:@“Height”值:@175];
NSArray*tableItems=[性别、年龄对、身高对];
看起来更清晰,但是。。。我认为这不是最好的解决方案(也没有类对,但是男人们会做一些设置,比如带开关的表格之类的,但是他们不知怎么做了)。我相信很多人都在尝试这样做,至少应该有一个更好的或通用的解决方案。

定义一个类:

@interface Human : NSObject

@property (nonatomic, strong) NSNumber* male; // Or a BOOL if you prefer it 
@property (nonatomic,strong) NSNumber* age; 
@property (nonatomic,strong) NSNumber* height; // Or NSString if you prefer it
                                 // Consider that you may always format the number

- (id) initWithAge: (NSNumber*) age height: (NSNumber*) height male: (NSNUmber*) male;

@end
始终可以请求对象的键:

Human* human=[[Human alloc] initWithAge: @20 height: @178 male: @YES];
NSNumber* age= [human valueForKey: @"age"];
编辑

对不起,我完全误解了你的问题。如果你总是对数组中的属性使用相同的位置,我想没有更好的方法了。
您可以轻松找到每一行的属性,因此也可以轻松返回表视图单元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell=[[UITableViewCell alloc]initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier: nil];
    Pair* pair= tableItems[ [indexPath indexAtPosition: 1] ];
    cell.textLabel.text= pair.key;
    cell.detailTextLabel.text= [NSString stringWithFormat: @"%@", pair.value];
    return cell;
}

这就是O(1):NSArray不是链表,您可以访问O(1)中的tableItems[index]来读取属性。

Key在表视图中有一个用粗体字编写的描述字符串。我已经有了这个类,问题是如何在表中格式化这个类的输出。你在问从这个类开始实现数据源的最佳方式是什么?是的,单元格标题的数据源和标题的值。值存储在类中。现在我想把它们链接到标题。这是一个用OSX制作的表格视图:你在iOS中也在找同样的吗?不。只是一个带有标题和子标题的简单的
UITableView