考虑到我有一个名为 ErrorViewController
的 UIViewController
,我正在使用 initWithNibName
进行实例化。
此 ErrorViewController
上有一个描述其“类型”的枚举。
这个 ErrorViewController
有一个委托(delegate)函数返回给它的委托(delegate),它会根据 ErrorViewController
上设置的类型做出响应。
在新的 initWithNibName
函数中传递所有参数,并在 ErrorViewController
上设置私有(private)属性是否更好。像这样:
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;
}
或者实例化对象然后像这样设置它的公共(public)属性会更好:
ErrorViewController *errorVc = [[ErrorViewController alloc]
initWithNibName:@"ErrorViewController" bundle:nil];
errorVc.delegate = self;
errorVc.type = kErrorTypeA.
关于委托(delegate)方法,最佳做法是通过传递参数来检查类型,还是通过检查传回的 Controller 的属性来检查类型,如下所示:
- (void)ErrorPage:(ErrorViewController *)ErrorPage
// check ErrorPage.errorType
}
或者这个: ?
- (void)ErrorPage:(ErrorViewController *)ErrorPage
andErrorType:(ErrorType)errorType
// check errorType
}
最佳答案
我认为这是一个偏好问题。如果对象在没有错误类型和/或委托(delegate)的情况下无法正常运行,最好提供您的自定义初始化程序。
关于你的第二个问题,我会像你的第二个例子一样提供错误类型。请注意,尽管方法名称应以小写字母开头(-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...
关于iphone - objective c 中创建对象和设置其属性的最佳实践是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17296831/