2011-07-04 116 views
1

我喜欢关于readwrite属性的一件事是,您可以免费获得KVO合规性,所以我倾向于在属性上使用它,即使它们只是从属性所属的对象内写入。另一方面,我知道如果一个属性的目的是可以被其他对象写入,那么它应该被设置为readwrite。所以,我应该用读写,即使我只能从自己的呼叫二传手:关于读写属性的问题

[self setFoo:bar]; 

替代(我认为)是使用:

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

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

回答

3

你可以在公共接口中声明一个属性readonly,然后在i中的类扩展中将其提升为readwrite mplementation文件。

了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 
0
在.H

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

然后

在.M

@synthesize foo; 

然后用像

[email protected]"madhu"; 

任何地方
[email protected]"mike"; 

但如果u合成像上面然后u必须始终使用像

自我与点

每次同时改变字符串

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. 

我认为其更好