关于读写属性的问题



我喜欢读写属性的一点是,你可以"免费"获得KVO遵从性,所以我倾向于在属性上使用它,即使它们只是从属性所属的对象内部写入。另一方面,我理解只有当一个属性打算被其他对象写入时,它才应该被设置为读写。那么,我应该使用读写吗即使我只从self:

调用setter
[self setFoo:bar];

另一种选择(我认为)是使用:

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

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

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

foo:

@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

in .h

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

在m

  @synthesize foo;

则在

之类的地方使用
  self.foo=@"madhu";

  self.foo=@"mike";

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

self with dot

每次改变字符串

   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.

我觉得这样更好