3

考虑到我有一个UIViewController调用ErrorViewController,我正在使用initWithNibName.

有一个ErrorViewController描述其“类型”的枚举。

ErrorViewController有一个委托函数,该函数返回其委托,该委托将根据ErrorViewController.

initWithNibName在新函数中传递所有参数并在ErrorViewController. 像这样:

ErrorViewController *errorVc = [[ErrorViewController alloc] 
initWithNibName:@"ErrorViewController" bundle:nil 
andErrorType:kErrorTypeA andDelegate:self];

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
andErrorType:(ErrorType)errorType andDelegate:(id<ErrorDelegate>)delegate{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.delegate = delegate;
        self.errorType = errorType;
    }
    return self;
}

还是最好实例化对象,然后像这样设置它的公共属性:

ErrorViewController *errorVc = [[ErrorViewController alloc] 
initWithNibName:@"ErrorViewController" bundle:nil];
errorVc.delegate = self;
errorVc.type = kErrorTypeA.

关于委托方法,最佳实践是通过传递参数来检查类型,还是通过检查传递回的 Controller 的属性,如下所示:

- (void)ErrorPage:(ErrorViewController *)ErrorPage 
// check ErrorPage.errorType
}

或这个: ?

- (void)ErrorPage:(ErrorViewController *)ErrorPage 
andErrorType:(ErrorType)errorType
// check errorType
}
4

1 回答 1

2

我认为这是一个偏好问题。如果对象在没有错误类型和/或委托的情况下无法正常运行,最好提供您的自定义初始化程序。

至于你的第二个问题,我会提供你第二个例子中的错误类型。请注意,方法名称应以小写字符开头(-errorPage:而不是-ErrorPage:)。

另外,如果你经常使用它,我会提供一个方便的类方法来创建对象:

+(ErrorViewController*) standardErrorViewControllerWithErrorType: (ErrorType) errorType andDelegate: (id<ErrorDelegate>) delegate {

  ErrorViewController *evc = [[ErrorViewController alloc] initWithNibName: @"ErrorViewController" bundle: nil andErrorType: errorType andDelegate: delegate];
return evc;
}

编辑

此外,在您的 init 方法中,鼓励使用-(instancetype) init...而不是-(id) init....

于 2013-06-25T12:30:14.940 回答