关于readwrite属性的问题

时间:2011-07-04 14:39:15

标签: cocoa

我喜欢readwrite属性的一件事是你可以免费获得KVO合规性,所以我倾向于在属性上使用它,即使它们只是从属性所属的对象内部写入。另一方面,我知道如果一个属性可以被其他对象写入,那么它应该只被设置为readwrite。所以,我应该使用readwrite,即使我只从self调用setter:

[self setFoo:bar];

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

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

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

2 个答案:

答案 0 :(得分:3)

您可以在公共接口中声明属性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

答案 1 :(得分:0)

in .h

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

然后

in .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.

我认为它更好