“实例变量"和“实例变量"之间是否存在差异?和“财产"在 Objective-C 中? [英] Is there a difference between an "instance variable" and a "property" in Objective-c?
问题描述
Objective-c 中的实例变量"和属性"有区别吗?
Is there a difference between an "instance variable" and a "property" in Objective-c?
我对此不太确定.我认为属性"是具有访问器方法的实例变量,但我可能认为错了.
I'm not very sure about this. I think that an "property" is an instance variable that has accessor methods, but I might think wrong.
推荐答案
属性是一个更抽象的概念.实例变量实际上只是一个存储槽,就像结构中的槽.通常其他对象永远不应该直接访问它们.另一方面,属性是可以访问的对象的属性(听起来很模糊,但它应该如此).通常一个属性会返回或设置一个实例变量,但它可以使用来自多个或根本不使用的数据.例如:
A property is a more abstract concept. An instance variable is literally just a storage slot, like a slot in a struct. Normally other objects are never supposed to access them directly. A property, on the other hand, is an attribute of your object that can be accessed (it sounds vague and it's supposed to). Usually a property will return or set an instance variable, but it could use data from several or none at all. For example:
@interface Person : NSObject {
NSString *name;
}
@property(copy) NSString *name;
@property(copy) NSString *firstName;
@property(copy) NSString *lastName;
@end
@implementation Person
@synthesize name;
- (NSString *)firstName {
[[name componentsSeparatedByString:@" "] objectAtIndex:0];
}
- (NSString *)lastName {
[[name componentsSeparatedByString:@" "] lastObject];
}
- (NSString *)setFirstName:(NSString *)newName {
NSArray *nameArray = [name componentsSeparatedByString:@" "];
NSArray *newNameArray [[NSArray arrayWithObjects:newName, nil] arrayByAddingObjectsFromArray:[nameArray subarrayWithRange:NSMakeRange(1, [nameArray size]-1)]];
self.name = [newNameArray componentsJoinedByString:@" "];
}
- (NSString *)setLastName:(NSString *)newName {
NSArray *nameArray = [name componentsSeparatedByString:@" "];
NSArray *newNameArray [[nameArray subarrayWithRange:NSMakeRange(0, [nameArray size]-2)] arrayByAddingObjectsFromArray:[NSArray arrayWithObjects:newName, nil]];
self.name = [newNameArray componentsJoinedByString:@" "];
}
@end
(注意:上面的代码有问题,因为它假设名称已经存在并且至少有两个组成部分(例如Bill Gates"而不仅仅是Gates").我觉得修复这些假设会使实际点代码不太清楚,所以我只是在这里指出它,所以没有人会无辜地重复这些错误.)
(Note: The above code is buggy in that it assumes the name already exists and has at least two components (e.g. "Bill Gates" rather than just "Gates"). I felt that fixing those assumptions would make the actual point of the code less clear, so I'm just pointing it out here so nobody innocently repeats those mistakes.)
这篇关于“实例变量"和“实例变量"之间是否存在差异?和“财产"在 Objective-C 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!