带有多个单元格的目标c-iphone列表视图



我已经能够使用下面的部分代码使列表视图显示单个数据字段。

NSMutableArray *array;
..
..
  array = [[NSMutableArray alloc] init];
  [array addObject:@"John Doe"];

但是,我想保留几个字段,例如:名称身份证件出生日期

我假设NSMutableArrary是一个NSString,但我需要一个类似于C中的结构的东西来保存我需要的字段。

ID将是"隐藏"的,但我需要在用户单击该行时访问它。如何访问ID和其他字段?我该如何设置,以便列表中包含信息?

有人有任何示例代码可以解释如何做到这一点吗?

编辑#1:感谢您的评论,但我对iPhone太陌生了,真的需要找到如何做到这一点的示例代码。虽然这些评论听起来像是可以做到这一点,但我不知道从哪里开始。有人能为3个字段的想法发布示例代码吗?

编辑#2:到目前为止,我已经尝试了所有的方法,正确的方法是这样做还是应该使用下面的想法?

Userrec.m

#import "UserRec.h"
@implementation Userrec
@synthesize Name, ID;
-(id)initWithName:(NSString *)n ID:(NSString *)d {
    self.Name = n;
    self.ID = d;
    return self;
}
@end

UserRec.h

#import <UIKit/UIKit.h>
@interface Userrec : NSObject {
NSString *Name;
NSString *ID;
}
@property (nonatomic, retain) NSString *Name;
@property (nonatomic, retain) NSString *ID;
-(id)initWithName:(NSString *)n ID:(NSString *)d;
@end

UserList.m

@synthesize userrecs;
…
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *Name = @"Name";
    NSString *ID = @"IID";
    Userrec *userrec = [[Userrec alloc] initWithName:Name ID:ID ];
    [userrecs addObject:userrec];
    NSLog(@"Count %d",[userrecs count]);
    [userrec release];
    NSLog(@"Count %d",[userrecs count]);
}

在我添加对象并检查计数后,它=0。所以我认为出了什么问题?

NSMutableDictionary是最好的方法。你可以做以下事情:

NSMutableDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"John Doe", @"Name", [NSNumber numberWithInt:5], @"ID", nil];

您可以使用同一模板继续添加任意数量的字段,甚至可以添加NSArray对象。如果你还有什么麻烦,我会查一下文件。请记住,您只能在NSDictionary中存储指向对象的指针。之类的东西

NSMutableDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"John Doe", @"Name", 5, @"ID", nil];

不会起作用。祝你好运

看看NSMutableDictionary,它似乎正是你想要使用的东西

编辑:这是的一些示例代码

NSMutableArray *myData = [[NSMutableArray alloc] init];
NSMutableDictionary *myRow = [[NSMutableDictionary alloc] init];
[myRow setObject:@"John Doe" forKey:@"Name"];
[myRow setObject:@"4738" forKey:@"ID"];
[myRow setObject:@"1/23/45" forKey:@"DOB"];
[myData addObject:myRow];
[myRow release];
//Repeat from dictioanry alloc through release for each row you need to add

要在UITableView中显示此信息,您需要有一个UITableViewController类。在那里覆盖cellForRowAtIndexPath:功能。这是功能的一个简单实现

-(UITableViewCell*) tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    static NSString *kCellID = @"cellID";
    UITableViewCell *cell = nil;
    cell = [tableView dequeueReuseableCellWithIdentifier:kCellID];
    if ( cell == nil )
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease];
    }
    NSMutableDictionary curRow = [myData objectAtIndex:row];
    cell.textLabel.text = [curRow objectForKey:@"Name"];
    return cell;
}

最新更新