【问题标题】:question about readwrite properties关于读写属性的问题
【发布时间】:2011-09-28 05:03:54
【问题描述】:

我喜欢读写属性的一点是,您可以“免费”获得 KVO 合规性,因此我倾向于在属性上使用它,即使它们只是从属性所属的对象中写入。另一方面,我知道只有在打算由其他对象写入时,才应将属性设置为 readwrite。所以,即使我只从自己调用 setter,我是否应该使用 readwrite:

[self setFoo:bar];

替代方案(我认为)是使用:

[self willChangeValueForKey:@"foo"];
foo = bar;
[self didChangeValueForKey:@"foo"];

这是我每次想要更改 foo 时都必须编写的额外两行代码。哪个更好?

【问题讨论】:

    标签: cocoa


    【解决方案1】:

    在.h中

       @property(nonatomic,readwrite,retain)NSString *foo;
    

    然后

    在.m

      @synthesize foo;
    

    然后在任何地方使用

      self.foo=@"madhu";
    

      self.foo=@"mike";
    

    但是如果你像上面那样合成,那么你必须总是像这样使用

    带点的自己

    每次更改字符串时

       it will automatically release the older object then retain the new one.so no pain to take care of old one for release and no pain for retain the new one.
    

    我觉得更好

    【讨论】:

      【解决方案2】:

      您可以在公共接口中声明属性readonly,然后在实现文件的类扩展中将其提升为readwrite

      Foo.h:

      @interface Foo: NSObject
      @property (readonly) NSString *frob;
      @end
      

      Foo.m:

      @interface Foo ()
      @property (readwrite) NSString *frob;
      @end
      
      @implementation Foo
      @synthesize frob;
      
      // Methods in Foo.m can now use foo.frob = @"whatever";
      @end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-19
        相关资源
        最近更新 更多