是否可能在视图控制器的init方法中使用块作为完成处理程序,以便父视图控制器能够填写块中的细节,而无需为每个可能的属性创建自定义initWithNibName:andResourceBundle:andThis:andThat:?
// ... in the didSelectRowAtIndexPath method of the main view controller :
SubViewController *subviewController = [[SubViewController alloc] initWithNibName:nil bundle:nil completionHandler:^(SubViewController * vc) {
vc.property1 = NO;
vc.property2 = [NSArray array];
vc.property3 = SomeEnumValue;
vc.delegate = self;
}];
[self.navigationController pushViewController:subviewController animated:YES];
[subviewController release];
在SubViewController.m中:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil completionHandler:(void (^)(id newObj))block {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
block(self);
}
return self;
}
替代
// ... in the didSelectRowAtIndexPath method of the main view controller :
SubViewController *subviewController = [[SubViewController alloc] initWithNibName:nil bundle:nil andProperty1:NO andProperty2:[NSArray array] andProperty3:SomeEnumValue andDelegate:self];
[self.navigationController pushViewController:subviewController animated:YES];
[subviewController release];
使用
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil andProperty1:(BOOL)p1 andProperty2:(NSArray *)p2 andProperty3:(enum SomeEnum)p3 andDelegate:(id<MyDelegateProtocol>)myDelegate {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.property1 = p1;
self.property2 = p2;
self.property3 = p3;
self.delegate = myDelegate;
}
return self;
}
这样,我就可以在主控制器中随心所欲地做任何事情,而不是调用预定义的初始化方法(并且必须为每种可能的初始化编写一个方法)。
这样做有什么不好吗?会出现保留环问题吗?