“实例变量"与“实例变量"之间是否有区别?以及“财产"在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
(注意:上面的代码有很多错误,因为它假定名称已经存在并且至少有两个组成部分(例如比尔·盖茨"而不是仅门").代码不太清楚,所以我只是在这里指出,所以没有人会无辜地重复这些错误.)
(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屋!