如何在Objective-C中强制执行只读的ivars?

时间:2012-06-26 09:35:09

标签: objective-c state

在我看来,状态类似于“活动部件”。事物越多,出错的机会就越多。我对国家持敌视态度。按照优先顺序,我想要一个州:

  1. 不存在的
  2. private readonly
  3. 私人& public readonly
  4. 私人读/写& public readonly
  5. 公开读/写
  6. 状态存储在ivar中(无论是通过@synthsize显式声明还是隐式声明)。为了允许公共访问状态,我们提供了访问器方法。在代码中表达上面的意图:

    1. 不写任何代码
    2. 使用ivar并依靠代码注释来防止(不是最佳!)
    3. 与2加上公共吸气剂相同
    4. ivar加上一个公共吸气者
    5. 4 plus public setter
    6. 如何更好地解决案例2?

2 个答案:

答案 0 :(得分:0)

首先,

  

实例变量/属性

ivars和属性不可互换。它们不是同一件事。属性可以由实例变量“支持”,但这是关系结束的地方。

首先,没有明确的实例变量。要实现第2点(或尽可能接近),请定义一个只读属性,并像这样@synthesize

@synthesize myProperty = myProperty_;

将实例变量(myProperty_)初始化为-init中所需的值,然后再不在.m文件中再分配给它。如果您不相信自己不能避免在{。{1}} -init {...}} {...}}之后将该文件分配到该.m文件中(尾随下划线可以帮助您)如果使用错误,例如

#define

答案 1 :(得分:-1)

//this is the guts of the solution. It is basically uses pointers to cast away the const.
#define EMK_INIT_READONLY_IVAR(ivar, value) (*(typeof(value) *)(&ivar) = value)


@interface Foo : NSObject
@end



@implementation
{
    id const _bar;
    const NSInteger _baz;
}



-(id)init
{
    self = [super init];
    if (self != nil)
    {
        //we could use KVC to set object values, but it's preferable to have a mechanism 
        //which is identical for object and scalar values.
        EMK_INIT_READONLY_IVAR(_bar, @"I got a brand new combine harvester, oh-ah, oh-ah!");
        EMK_INIT_READONLY_IVAR(_baz, 0xDEADBEEF);
    }
    return self;
}

@end