2011-08-01 24 views
1

我試圖讓自定義筆尖文件做UITableViewCell的子類的掛。自定義UITableViewCell:SIGABRT「loadNibNamed:」

子類的名稱是MyCustomCell。 .xib文件只有一個具有單個UILabel「cellTitle」的UITableViewCell,並且我已將它連接到UITableViewCell子類中的插座。

在MyCustomCell類返回小區,我得到一個SIGABRT錯誤以下行:

NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:NULL]; 

這裏的cellForRowAtIndexPath執行:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

{ 
static NSString *kCustomCellID = @"MyCellID"; 

myCustomCell *cell = (myCustomCell *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID]; 
if (cell == nil) 
{ 
    cell = (myCustomCell *)[myCustomCell cellFromNibNamed:@"myCustomCell"]; 
} 
//TODO: Configure Cell 
return cell; 
} 

下面是myCustomCell cellFromNibNamed實施:

+ (myCustomCell *)cellFromNibNamed:(NSString *)nibName 
{ 
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:NULL]; 
NSEnumerator *nibEnumerator = [nibContents objectEnumerator]; 
myCustomCell *customCell = nil; 
NSObject* nibItem = nil; 
while ((nibItem = [nibEnumerator nextObject]) != nil) 
    { 
    if ([nibItem isKindOfClass:[myCustomCell class]]) 
     { 
     customCell = (myCustomCell *)nibItem; 
     break; // we have a winner 
     } 
    } 
return customCell; 
} 

我得到了SIGABRT錯誤線

NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:NULL]; 

上述方法。我在這裏做錯了什麼?

回答

4
約從@Seega你的筆尖名字聲明

除了這似乎是合理的,你必須在筆尖裝載許多問題碼;

+ (myCustomCell *)cellFromNibNamed:(NSString *)nibName 
{ 
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"View" owner:self options:NULL]; 
NSEnumerator *nibEnumerator = [nibContents objectEnumerator]; 
myCustomCell *customCell = nil; 
NSObject* nibItem = nil; 
while ((nibItem = [nibEnumerator nextObject]) != nil) 
    { 
    if ([nibItem isKindOfClass:[myCustomCell class]]) 
     { 
     customCell = (myCustomCell *)nibItem; 
     break; // we have a winner 
     } 
    } 
return customCell; 
} 

customCell情況下是零,以便在發送的class方法是無操作,並返回零。在這種情況下,isKindOfClass:不會返回您的想法。

此外,不要遍歷從loadNibNamed:owner:options:方法返回的對象列表。相反,在文件的所有者和nib文件中的單元格之間建立連接,以便在nib加載時設置它。然後改變你的代碼看起來像這樣;

+ (myCustomCell *)cellFromNibNamed:(NSString *)nibName { 
    [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:NULL]; 
    myCustomCell *gak = self.theFreshlyLoadedCustomCellThingSetUpInIB; 
    // clean up 
    self.theFreshlyLoadedCustomCellThingSetUpInIB = nil; 
    return gak; 
} 

此外,使用小寫字符命名類是非典型的。其他人閱讀你的代碼會認爲這是一個變量,而不是一個類。改爲撥打MyCustomCell

+0

你能解決您self.theFreshlyLoadedCustomCellThingSetUpInIB是什麼意思?在我看到的例子中,人們或者遍歷nib的內容,或者簡單地使用objectAtIndex:0,因爲他們認爲它應該在那裏,因爲沒有別的東西應該在那裏。 – Ascendant

+0

當然,在指向表格視圖單元格的上方(視圖控制器?)類中設置了一個出口。加載單元格時,NSBundle代碼會將該出口設置爲單元格。 –

1

我認爲你應該使用字符串參數「nibName」,而不是@「查看」

NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:NULL]; 
1

正如人們指出的那樣,我的代碼中存在一些問題。導致我在標題中討論的實際問題的問題在IB中證明是一個問題:我有插座引用文件的所有者而不是實際的對象。

但是我給這一個法案,因爲他談到失誤的數量最多......