iPhone开发中的Objective-C属性 [英] Objective-C Properties in iPhone Development

查看:45
本文介绍了iPhone开发中的Objective-C属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Objective-C中的属性和实例变量之间有什么区别?我需要用OOP术语来理解这一点.属性声明仅仅是访问实例变量的便捷包装(在实现中带有@synthesize)吗?

Whats the difference between a property and an instance variable in Objective-C. I need to understand this in OOP terms. Is a property declaration just a convenience wrapper (with @synthesize in the implementation) for accessing instance variables?

谢谢

codecowboy.

codecowboy.

推荐答案

属性和ivars是完全不同的两件事.

Properties and ivars are two completely different things.

实例变量是存储在对象内部的变量,因此每个实例都有自己的变量.通过相对于对象指针/自身的指针添加来引用它(在现代运行时中略为间接,但在功能上等效). ivars通常位于类的内部,默认情况下,只能由该类及其后代(@protected)访问.在方法内,它们是无条件可用的,否则可以通过间接访问(例如obj-> ivar)来访问(但很少有,通常不应使用).

And instance variable is a variable stored inside the object, so each instance has its own. It is referenced by pointer addition relative to the object pointer/self (slightly indirected for the modern runtime, but functionally equivalent). ivars are generally internal to a class, and by default can only be accessed by the class and its descendents (@protected). Within methods they are available with no qualification, otherwise they can (but rarely are, ad usuaually should not) be accessed via indirection, eg obj->ivar.

一个属性定义了一个getter和setter(setter是可选的)接口.这就是全部.它定义了两种公共方法:

A property defines a getter and setter (the setter is optional) interface. That's all it does. It defines two public methods:

- (TYPE) propname;
- (void) setPropname: (TYPE) newPropname;

这些被定义为方法,就像您这样声明它们一样,不多也不少.可以使用常规语法([obj propname]和[obj setPropname:n])或现代点表示法(obj.propname或obj.propname = n)来调用这些方法.这两个选项在语法上仅是不同的,它们的行为相同,无论方法是使用@property声明还是如上所述手动声明,您都可以使用点表示法.

These are defined as methods exactly as if you declared them like that, no more, no less. These methods are called either with the normal syntax ([obj propname] and [obj setPropname:n] or using the modern dot notation (obj.propname or obj.propname = n). These two options are syntactically different only, they behave identically, and you can use dot notation whether the methods are declared with @property or declared manually as above.

然后必须通过自己编写方法,使用@synthesize或动态处理缺少的方法来实现实现中的方法.

You must then implement the methods in the implementation, either by writing the methods yourself, by using @synthesize, or by handling the missing method dynamically.

属性可以由一个ivar(名称相同或名称不同(我倾向于避免混淆))支持,也可以不支持.他们可以将其值存储在其他位置,也可以根据其他数据进行计算.

Properties may be backed by an ivar (named the same or named differently (my preference to avoid confusion)), or they may not. They may store their value elsewhere, or they may calculate it from other data.

例如,您可能有:

@property (nonatomic, readonly) NSString* fullname;

然后实现-(NSString *)全名,以返回名和姓的串联.

and then implement - (NSString*) fullname to return the concatenation of firstname and lastname.

这篇关于iPhone开发中的Objective-C属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆