关于IOS中变量声明方式@interface和@property的区别
1个回答
展开全部
只在@interface中定义变量的话,你所定义的变量只能在当前的类中访问,在其他类中是访问不了的;而用@property声明的变量可以在外部访问。
2.用了@property去声明的变量,可以使用“self.变量名”的方式去读写变量。而用@interface的方式就不可以。
3. 里面讲到: 我英语菜,简单翻一下:
Defining the variables in the brackets simply declares them instance variables.
在括号中定义一个变量只是简单的声明了一个实例变量(实例变量应该指的成员变量)。 博主注:老外对variable 和instance variable是有不同理解的。所以下文中 用了一个模糊的词 ivar。
Declaring (and synthesizing) a property generates getters and setters for the instance variable, according to the criteria within the parenthesis. This is particularly important in Objective-C because it is often by way of getters and setters that memory is managed (e.g., when a value is assigned to an ivar, it is by way of the setter that the object assigned is retained and ultimately released). Beyond a memory management strategy, the practice also promotes encapsulation and reduces the amount of trivial code that would otherwise be required.
声明(和 @synthsize)一个属性会为成员变量生成 getter 和setter方法,根据括号内的标准,在oc中经常用setter和getter 做内存管理,这是很重要的。(例如: 当一个值被赋给这个变量,对象是通过setter函数去分配,修改计数器,并最后释放的)。更高一个层次来说,这种做法也促进了封装,减少了一些不必要的 代码。
It is very common to declare an ivar in brackets and then an associated property (as in your example), but that isn’t strictly necessary. Defining the property and synthesizing is all that’s required, because synthesizing the property implicitly also creates an ivar.
在@interface括号中定义一个变量并用@property 重复定义一次是很普遍的,实际上不是必要的。用@property和@synthszie就够了,因为在用@synthsize合成这个属性的读写方法时就会创建一个变量。
2.用了@property去声明的变量,可以使用“self.变量名”的方式去读写变量。而用@interface的方式就不可以。
3. 里面讲到: 我英语菜,简单翻一下:
Defining the variables in the brackets simply declares them instance variables.
在括号中定义一个变量只是简单的声明了一个实例变量(实例变量应该指的成员变量)。 博主注:老外对variable 和instance variable是有不同理解的。所以下文中 用了一个模糊的词 ivar。
Declaring (and synthesizing) a property generates getters and setters for the instance variable, according to the criteria within the parenthesis. This is particularly important in Objective-C because it is often by way of getters and setters that memory is managed (e.g., when a value is assigned to an ivar, it is by way of the setter that the object assigned is retained and ultimately released). Beyond a memory management strategy, the practice also promotes encapsulation and reduces the amount of trivial code that would otherwise be required.
声明(和 @synthsize)一个属性会为成员变量生成 getter 和setter方法,根据括号内的标准,在oc中经常用setter和getter 做内存管理,这是很重要的。(例如: 当一个值被赋给这个变量,对象是通过setter函数去分配,修改计数器,并最后释放的)。更高一个层次来说,这种做法也促进了封装,减少了一些不必要的 代码。
It is very common to declare an ivar in brackets and then an associated property (as in your example), but that isn’t strictly necessary. Defining the property and synthesizing is all that’s required, because synthesizing the property implicitly also creates an ivar.
在@interface括号中定义一个变量并用@property 重复定义一次是很普遍的,实际上不是必要的。用@property和@synthszie就够了,因为在用@synthsize合成这个属性的读写方法时就会创建一个变量。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询