@property和@private及在.m文件中声明变量的区别
来源:互联网 发布:linux 删除过期文件 编辑:程序博客网 时间:2024/06/05 09:05
1.@private在.h文件中声明的变量
(1)在.h文件中使用@private声明的成员变量,子类是可以继承的,但不能直接访问
(2)在.h文件中使用@private声明的成员变量,分类是可以直接访问的
<a>继承关系
Person类声明:
@interface Person : NSObject{ @private NSString *_name;}@end
Person的实现:
@implementation Person@end
子类Student的声明:
@interface Student : Person-(void) play;@end
子类Student的实现:
可以看到在子类Student中继承了父类Person的_name属性,但是不能直接访问
<b>分类
Person的分类声明:
@interface Person (play)-(void) play;@end
Person的分类实现:
可以看到上面的分类中可以访问Person类中@private修饰的属性_name
2.在.m文件中声明变量
在.m文件中声明的变量是私有的,且不能被继承和被分类访问
例:
Person类:
@implementation Person{ NSString *_name;}@end
子类Student:
分类
所以,在.m文件中声明的属性是真正的私有化了,
所以,老外的一些建议是:
如果只是单纯的private变量,最好声明在implementation里.
如果是类的public属性,就用property写在.h文件里
如果自己内部需要setter和getter来实现一些东西,就在.m文件的类目里用property来声明
3.@property声明的变量
使用@property声明的变量实际上就如在.m文件中声明的变量一样,是真正私有化的,@property声明的变量做了三件事,1.在.ml文件中声明一个@private的变量(不是在.h文件中声明@private变量),2.声明setter和getter方法,3.定义setter和getter的实现
( 1)使用@property声明的变量,子类是不能继承的,分类是不能直接访问的
例:
Person类的声明:
@interface Person : NSObject@property (nonatomic ,retain) NSString *name;@end
Person类的实现:
@implementation Person@end
Student子类:
Person的分类:
0 0
- @property和@private及在.m文件中声明变量的区别
- objective_C中@interface和 @property 方式声明变量的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- iOS OC声明变量在@interface括号中与使用@property的区别
- iOS声明变量在@interface括号中与使用@property的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- IOS OC声明变量在@interface括号中与使用@property的区别
- iOS声明变量在@interface括号中与使用@property的区别
- Linux xargs命令
- 装配线问题—类似于树形dp的解法
- 项目开发——你该注意什么?
- Grey's Anatomy第十季
- 集合元素的排列和组合
- @property和@private及在.m文件中声明变量的区别
- Linux中find常见用法示例
- 有关R关系网络图中init.igarph的生成
- 图的存储结构——邻接矩阵
- jd尝试抓一个页面
- Android之自制的分页表格控件 .
- shell编程必须要掌握的命令,xargs
- ANSYS命令
- oralce无法删除用户ORA-01940 无法删除连接用户