【问题标题】:ObjectiveC: where to declare private instance properties?ObjectiveC:在哪里声明私有实例属性?
【发布时间】:2012-07-03 11:54:36
【问题描述】:

我有如下类接口:

@interface MyClass : NSObject

@property int publicProperty;

@end

然后是实现:

@interface MyClass() // class extension

- (void)privateMethod; // private methods

@end

@implementation MyClass {
    int _privateProperty;
}

@property int privateProperty = _privateProperty;

@end

这是苹果人在 WWDC 中展示的内容,但有什么理由不将 _privateProperty 放在类扩展中,例如:

@interface MyClass() // class extension
{
    int _privateProperty;
}

- (void)privateMethod; // private methods

@end

谢谢!

【问题讨论】:

标签: objective-c implementation private class-extensions


【解决方案1】:

你不必在接口和实现中都声明你的 ivars。因为你想让它们私有,你可以像这样在实现文件中声明它们:

@implementation {

int firstVariable;
int secondVariable;
...
}
//properties and code for  your methods

如果您愿意,您可以创建 getter 和 setter 方法,以便访问这些变量。

与您交谈的人是对的,尽管您没有任何理由不在界面中以相同的方式声明它们。有些书实际上告诉你,@interface 显示了类的公共面孔,而你在实现中拥有的内容将是私有的。

【讨论】:

    【解决方案2】:

    我通常在实现中通过扩展“强制”私有

    在您的标题中

    @interface MyClass : NSObject
    {
    }
    
    @property (nonatomic, assign) int publicProperty;
    
    @end
    

    在你的实现文件中:

    @interface MyClass ()
    @property (nonatomic, assign) int privateProperty;
    @end
    
    
    @implementation MyClass
    @synthesize privateProperty;
    @synthesize publicProperty;
    
    @end
    

    【讨论】:

      【解决方案3】:

      使用“现代运行时”(64 位 MacOS post-10.5 和所有版本的 iOS),您根本不需要声明实例变量。

      // MyClass.h
      @interface MyClass : NSObject
      
      @property int publicProperty;
      
      @end
      
      
      // MyClass.m
      @implementation MyClass
      
      @synthesize publicProperty = _privateProperty;  // int _privateProperty is automatically synthesized for you.
      
      @end
      

      【讨论】:

        【解决方案4】:

        你的意思是要声明私有实例变量?

        你可以这样做:

        @interface MyClass()
        {
         @private //makes the following ivar private
           int _privateProperty;
        }
        

        【讨论】:

        • 是的,但我不想让它成为 ivar,它只是一个可以通过 self.privateProperty 使用访问器访问的属性,而不是暴露在 @interface 中。
        • 这个@property int privateProperty = _privateProperty;是不行的,你得在实现文件里做。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-05
        • 2012-02-08
        • 2021-08-05
        • 1970-01-01
        • 2015-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多