2013-09-29 42 views
2

1)我使用的單一視圖的應用開始在Xcode中一個新的項目被調用。的UITableViewController過程初始化函數不使用時,故事板

2)I刪除默認視圖控制器和增加了一個新的UITableViewController

3)在情節串連圖板,我拖出一個UITableViewController並將其設置爲我剛創建

4的一個)設置重用標識符

在我的代碼我試圖重寫init方法做一些設置。爲什麼我的自定義init方法不被調用?當你使用storyboard,並拖出一個UITableViewController並將其設置爲一個自定義類時,你是否可以不重寫initWithStyle:方法?當我把設置放在viewDidLoad中時,它就起作用了。

這裏是視圖控制器的代碼:

#import "ItemsViewController.h" 
#import "BNRItem.h" 
#import "BNRItemStore.h" 

@implementation ItemsViewController 

- (id)init 
{ 
    // Call the superclass's designated initializer 
    self = [super initWithStyle:UITableViewStyleGrouped]; 
    if (self) { 
     for (int i = 0; i < 10; i++) { 
      [[BNRItemStore defaultStore] createItem]; 
      NSLog(@"Test init"); 
     } 
    } 
    return self; 
} 

- (id)initWithStyle:(UITableViewStyle)style 
{ 

    NSLog(@"test init style"); 
    return [self init]; 
} 

- (NSInteger)tableView:(UITableView *)tableView 
numberOfRowsInSection:(NSInteger)section 
{ 
    NSLog(@"test tableview rowsinsection"); 
    return [[[BNRItemStore defaultStore] allItems] count]; 

} 


- (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSLog(@"test tableview cellforrow"); 
    // Create an instance of UITableViewCell, with default appearance 
    // Check for a reusable cell first, use that if it exists 
    UITableViewCell *cell = 
    [tableView dequeueReusableCellWithIdentifier:@"itemsCell"]; 

    // If there is no reusable cell of this type, create a new one 
    if (!cell) { 
     cell = [[UITableViewCell alloc] 
       initWithStyle:UITableViewCellStyleDefault 
       reuseIdentifier:@"itemsCell"]; 
    } 
    // Set the text on the cell with the description of the item 
    // that is at the nth index of items, where n = row this cell 
    // will appear in on the tableview 
     [[cell textLabel] setText:@"Hello"]; 
    return cell; 
} 
@end 

回答

5

初始化僅當使用[[類的alloc] INIT]你稱爲

可以覆蓋

- (void)awakeFromNib 



awakeFromNib 
Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file. 

- (void)awakeFromNib 
Discussion 
An awakeFromNib message is sent to each object loaded from the archive, but only if it can respond to the message, and only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet instance variables set. 
+0

謝謝使用awakeFromNib工作來完成數據設置。啊,所以當使用storyboard創建視圖控制器時,init方法不會被調用。這是一個棘手的事情要小心。 – nearpoint

相關問題