属性与实例变量 [英] Property vs. instance variable
问题描述
我想了解一些人如何使用策略来区分实例vars和属性。一个常见的模式如下:
I'm trying to understand how strategies some folks use to distinguish instance vars vs. properties. A common pattern is the following:
@interface MyClass : NSObject {
NSString *_myVar;
}
@property (nonatomic, retain) NSString *myVar;
@end
@implementation MyClass
@synthesize myVar = _myVar;
现在,我认为这个策略背后的整个前提是, ivar和财产。所以,如果我想使用由合成属性继承的内存管理,我会使用如下:
Now, I thought the entire premise behind this strategy is so that one can easily distinguish the difference between an ivar and property. So, if I want to use the memory management inherited by a synthesized property, I'd use something such as:
myVar = @"Foo";
另一种方法是通过self [ivar / property here]引用它。
The other way would be referencing it via self.[ivar/property here].
使用@synthesize myVar = _myVar策略的问题是我认为编写代码如:
The problem with using the @synthesize myVar = _myVar strategy, is I figured that writing code such as:
myVar = some_other_object; // doesn't work.
编译器提示myVar未声明。为什么会这样?
The compiler complains that myVar is undeclared. Why is that the case?
感谢。
推荐答案
属性
@interface APerson : NSObject {
// NSString *_name; // necessary for legacy runtime
}
@property(readwrite) NSString *name;
@end
@implementation APerson
@synthesize name; // use name = _name for legacy runtime
@end
@synthesize
在这种情况下创建这两种方法(不是100%准确):
@synthesize
creates in this case those two methods (not 100% accurate):
- (NSString *)name {
return [[_name copy] autorelease];
}
- (void)setName:(NSString *)value {
[value retain];
[_name release];
_name = value;
}
现在很容易区分 ivars
和getters / setters。访问器有 self。
前缀。
It's easy now to distinguish between ivars
and getters/setters. The accessors have got the self.
prefix. You shouldn't access the variables directly anyway.
您的示例代码不工作,因为它应该是:
Your sample code doesn't work as it should be:
_myVar = some_other_object; // _myVar is the ivar, not myVar.
self.myVar = some_other_object; // works too, uses the accessors
这篇关于属性与实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!