1)我使用单一视图应用程序在xcode中启动了一个新项目。
2)我删除了默认的视图控制器并添加了一个新的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
答案 0 :(得分:5)
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.