您可以使用自定義類作爲文件的所有者,但您不必。我將向您展示兩種從NIB加載表格單元的技術,一種使用文件所有者,另一種不使用。
不使用文件的所有者,這裏是從NIB加載表格單元格的方式:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:@"MyID"];
if (!myCell) {
NSBundle *bundle = [NSBundle mainBundle];
NSArray *topLevelObjects = [bundle loadNibNamed:@"MyNib" owner:nil options:nil];
myCell = [topLevelObjects lastObject];
}
/* setup my cell */
return myCell;
}
上面的代碼是脆弱的,因爲在未來,如果你修改XIB有更多的頂級對象,這段代碼可能會通過從「[topLevelObjects lastObject]」獲取錯誤的對象而失敗。儘管如此,它並不脆弱,所以這種技術很好用。
要多一點明確的和穩健的,您可以使用文件的所有者和出口,而不是使用頂級對象。這裏有一個例子:
@interface MyTableViewDataSource : NSObject {
UITableViewCell *loadedCell;
}
@property (retain) UITableViewCell *loadedCell;
@end
@implementation MyTableViewDataSource
@synthesize loadedCell;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:@"MyID"];
if (!myCell) {
[[NSBundle mainBundle] loadNibNamed:@"MyNib" owner:self options:nil];
myCell = [[[self loadedCell] retain] autorelease];
[self setLoadedCell:nil];
}
/* setup my cell */
return myCell;
}
@end
我使用的是第一種方法,因爲它似乎被許多開發中使用...但是,我更喜歡第二個,因爲它最終給了我什麼,我們可以更多的控制在自定義類中放置更多的init代碼....更多面向對象的... – JFMartin 2009-08-18 00:29:32