【问题标题】:What is Best practice in objective c for creating an object and setting its properties什么是目标 c 中创建对象并设置其属性的最佳实践
【发布时间】:2013-06-25 12:03:13
【问题描述】:

考虑到我有一个名为ErrorViewControllerUIViewController,我正在使用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
}

【问题讨论】:

    标签: iphone objective-c uiviewcontroller enums


    【解决方案1】:

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

    至于您的第二个问题,我将提供您第二个示例中的错误类型。请注意,方法名称应以小写字符开头(-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....

    【讨论】:

    • 另外,“and”实际上已经用在方法名中了。 (即使用委托而不是andDelegate。)
    • 没错(猜你的意思是“没有真正使用”)!我也想指出这一点,但只是收集了它的个人喜好,因此坚持了 OP 风格。
    • 可以在here 找到很多关于这个和类似问题的“最佳实践”内容
    • 实际上,我的意思是“很少使用”,但自动更正让我明白了,哈哈!
    • @Mario,伟大的方向,而 Filip,将阅读那篇文章,实际上这是我一段时间以来一直在寻找的东西。
    猜你喜欢
    • 1970-01-01
    • 2011-01-07
    • 2011-12-27
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多