【问题标题】:UITableViewController over-ride init function not being called when using storyboard使用情节提要时未调用 UITableViewController 覆盖初始化函数
【发布时间】:2013-09-29 04:42:00
【问题描述】:

1) 我使用单视图应用程序在 xcode 中启动了一个新项目。

2) 我删除了默认的视图控制器并添加了一个新的 UITableViewController

3) 在故事板中,我拖出一个 UITableViewController 并将其设置为我刚刚创建的那个

4) 设置复用标识符

在我的代码中,我尝试重写 init 方法来进行一些设置。为什么我的自定义初始化方法没有被调用?当您使用故事板时,您将 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

【问题讨论】:

    标签: ios objective-c uitableview


    【解决方案1】:

    只有在使用 [[class alloc] init] 时才会调用 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.
    

    【讨论】:

    • 谢谢,使用 awakeFromNib 可以进行数据设置。啊,是的,所以当使用情节提要创建视图控制器时,不会调用 init 方法。这是一件需要注意的棘手事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    相关资源
    最近更新 更多