是否可以在视图控制器的 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;
}
这样我就可以在主控制器中做任何我想做的事情,而不是调用预定义的 init 方法(并且必须为每个可能的初始化编写一个)。
有什么不好的吗?会有保留周期吗?