您可以利用創建自定義類的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