您可以利用创建自定义类的oop样式(例如DataItem
)并使用DataItem
元素初始化您显示的数组。换句话说,您可以创建一个包含名称和图像元素的模型。
例如:
//.h
@interface DataItem : NSObject
{
NSString* name;
NSString* thunbmail;
}
@property (nonatomic, copy) NSString* name;
@property (nonatomic, copy) NSString* thunbmail;
- (id)initWithName:(NSString*)dName withThunbmail:(NSString*)dThunbmail;
@end
//.m
@implementation DataItem
@synthesize name;
@synthesize thunbmail;
- (id)initWithName:(NSString*)dName withThunbmail:(NSString*)dThunbmail
{
if(self = [super init])
{
name = [dName copy]; // release in dealloc!!
thunbmail = [dThunbmail copy]; // release in dealloc!!
}
return self;
}
// create dealloc here
@end
现在你可以初始化一个物品,并把它添加到阵列(也可能是最好有一个NSMutableArray
)像下面这样:
DataItem* di = [[DataItem alloc] initWithName:@"name" withThunbmail:@"image.png"];
NSMutableArray* arrData = [[NSMutableArray alloc] init];
[arrData addObject:di];
// add other object here
self.tableData = arrData;
// release memory...
,然后在cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell..
DataItem* di = (DataItem*)[self.tableData objectAtIndex:[indexPath row]];
cell.textLabel.text = di.name;
cell.imageView.image = [UIImage imageNamed:di.thunbmail];
return cell;
}
这是一种优雅的方式来封闭你的cont在一个单一的班级模型。
希望它有帮助。
P.S.检查代码。我手写的。
您创建的cellForRowAtIndexPath单独的UITableViewCell实例:这是UITableViewDataSource协议的一部分。 – Rayfleck 2012-02-07 13:15:10