【问题标题】:Controlling access to instance variables in Objective-C在 Objective-C 中控制对实例变量的访问
【发布时间】:2015-04-13 09:24:45
【问题描述】:

从我看到的所有代码中,几乎总是使用类似这样的方式来定义属性范围:

类扩展

/*We declare the class extension*/
@interface  MyClass () 

@property (nonatomic, retain) Type *aPrivateProperty; 
- (void)aPrivateMethod;

@end

/*
We can use the main implementation block to implement our properties
and methods declared in the class extension.
*/
@implementation MyClass

/*Therefore we can use synthesize ;-)*/
@synthesize aPrivateProperty;

- (void)aPrivateMethod {        
    //Some code there
}

@end

但这(据我所见)很少使用:

@interface MyClass : NSObject {
    iVar *aProtectedIVar;
    @public
    iVar *aPublicIVar;
    iVar *aSecondPublicIVar;
    @protected
    iVar *aSecondProtectedIVar;
    @private
    iVar *aPrivateIVAr;
}

@end

如果 @private、@protected 和 @public 等修饰符可用,为什么它们在 Objective-C 中没有被大量使用?

【问题讨论】:

    标签: objective-c class properties scope ivar


    【解决方案1】:

    很少使用实例变量的访问修饰符,因为它们公开的有关对象结构的信息比您希望其他人看到的要多。公共变量的公开将绑定到所有未来的实现以具有相同的变量。另一方面,属性隐藏了变量,让您稍后改变主意,计算结果而不是存储它。

    Objective-C 对属性访问进行了高度优化,因此公开属性而不是变量几乎不会在运行时受到影响。由于您可以通过切换到属性免费获得灵活性,因此很少使用 @public 公开变量。

    我很感兴趣为什么类扩展(如上面的示例)比@private 修饰符更常用

    因为类扩展允许您使用 .m 文件而不是 .h 头文件放置私有属性。其他 .m 文件中包含的头文件会创建编译时依赖项,通过将实现细节放入类扩展中可以轻松避免这种情况。

    【讨论】:

    • 我想我明白你在说什么。我的问题也不太清楚......我很感兴趣为什么类扩展(如上面的示例)比@private 修饰符更频繁地使用。 (@public 对于这个问题真的不重要)。
    【解决方案2】:

    你可以在三个地方声明一个全局变量。 如果您在 .h 中声明它是公开的:

    @property (nonatomic, strong) NSString *publicString; 
    

    相反,如果您在 .m 中声明相同的是私有的,则不需要第二种方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 2023-04-04
      相关资源
      最近更新 更多