第一件事,你的代碼泄漏了。刪除兩個電話retain
。
其次,您在基於相同信息的多個交換機/ if..else鏈中存在經典問題。這是一個面向對象解決方案的尖叫。
首先創建一個TableSection類:
@interface TableSection : NSObject
{ }
@property (nonatomic, copy) NSString* header;
@property (nonatomic, copy) NSArray* rows;
- (NSInteger)numberOfRows;
- (UITableViewCell*)cellInTableView: (UITableView*)tableView forRow: (NSInteger)row;
@end
@implementation TableSection
@synthesize header;
@synthesize rows;
- (void)dealloc {
[header release];
[rows release];
[super dealloc];
}
- (NSInteger)numberOfRows {
return rows.count;
}
- (UITableViewCell*)cellInTableView: (UITableView*)tableView forRow: (NSInteger)row {
// create/reuse, setup and return a UITableViewCell
}
@end
現在,在您TableViewController
@interface MyViewController : UITableViewController
{ }
@property (nonatomic, retain) NSArray* tableSections;
@end
@implementation MyViewController
- (void)dealloc {
[tableSections release];
[super dealloc];
}
- (void)viewDidLoad {
TableSection* section1 = [[TableSection alloc] init];
[section1 setRows: [NSArray arrayWithObjects: @"Send SMS", @"Reports", nil]];
TableSectlion* section2 = [[TableSection alloc] init];
[section2 setRows: [NSArray arrayWithObjects: @"Accounts", nil]];
[self setTableSections: [NSArray arrayWithObjects: section1, section2, nil]];
[section2 release];
[section1 release];
}
- (void)viewDidUnload {
[self setTableSections: nil];
}
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView: (UITableView*)tableView {
return self.tableSections.count;
}
- (NSInteger)tableView: (UITableView*)tableView numberOfRowsInSection: (NSInteger)section {
return [[self.tableSections objectAtIndex: section] numberOfRows];
}
- (UITableViewCell*)tableView: (UITableView*)tableView cellForRowAtIndexPath: (NSIndexPath*)indexPath {
return [[self.tableSections objectAtIndex: indexPath.section] cellInTableView: tableView forRow: indexPath.row];
}
- (NSString*)tableView: (UITableView*)tableView titleForHeaderInSection: (NSInteger)section {
return [[self.tableSections objectAtIndex: section] header];
}
@end
你可以發佈代碼cellForRowAtIndexPath – visakh7 2011-03-18 11:46:50
在你的示例代碼中,你將有很多內存泄漏。例如,最好在viewDidLoad中創建數組。因爲您需要通過幾種方法訪問數組。查看@fluchtpunkt的答案。 – 2011-03-18 12:32:32