【问题标题】:What's the difference between adding pseudo-private ivars in a class extension or in the @implementation block?在类扩展或 @implementation 块中添加伪私有 ivars 有什么区别?
【发布时间】:2012-02-03 01:07:43
【问题描述】:

将伪私有实例变量放在 .m 文件内的类扩展中,或者将它们放在新引入的@implementation 括号中,如下所示有什么区别?

其中一种或另一种方式是否有后果、优点、缺点? internal2 是否以程序员必须关心的方式与 internal3 区别对待? (当然,McKay 会说有所不同,但问题是你在实践中是否关心)。

// MyClass.m

@interface MyClass () {
    id internal2;
}
@end


@implementation MyClass {
    id internal3;
}

- (void)internalMethod {
    NSLog(@"%@ %@", internal2, internal3);
}

@end

来源:http://www.mcubedsw.com/blog/index.php/site/comments/new_objective-c_features/

【问题讨论】:

    标签: objective-c ios


    【解决方案1】:

    这两种方法的主要区别在于您可以将类扩展包含在单独的标头中,而 @implementation ivars 显然必须与 .m 文件中的 @implementation 块一起使用(并且只能有一个 @给定类的实现(不包括扩展))。这样做的实际结果是您可以拥有多个级别的“私有” ivars:

    • MyClass.h:公共 ivars
    • MyClass+Private.h:半私有 ivars
    • MyClass.m:真正的私有 ivars

    作为一个假设的例子,假设 MyClass 是 UIView。在这种情况下,UIView.h 是我们都可以访问的标头,UIView+Private.h 是只有 Apple 才能访问的“私有”标头,而 UIView.m 包含只有专门负责 UIView 的人需要知道的内容关于。

    【讨论】:

    • 类可以有多个实现块。它是类扩展的基础。
    • 是的,当然。但是不涉及类别,单个类只能有一个@implementation。
    • @EllNeal: 类别@implementations != 类别@implementations
    • 同意。但是如果不包括类别,“只能有一个 @interface 对于给定的类” 也是正确的 - 您的编辑虽然可以清除它;)
    【解决方案2】:

    就个人而言,我更喜欢将我的 ivars 放在实现文件中的单个类扩展中,我认为这样更干净。我不认为使用其中一种有任何性能优势或后果,更多的是能够按照您想要的方式进行编码。

    【讨论】:

      猜你喜欢
      • 2017-06-11
      • 2016-11-23
      • 2012-08-11
      • 2019-07-13
      • 1970-01-01
      • 2018-03-14
      • 2011-12-25
      • 2017-11-13
      相关资源
      最近更新 更多