第一部分 实例变量作用域
一、基本分类
1、@public,修饰的实例变量可以在任何位置被访问。
@interface Person : NSObject
{
@public //公共变量
int _age;
}
- (void)test;
@end
@implementation Person
- (void)test
{
_age = 10; //直接访问
}
@end
int main()
{
Person *p = [Person new];
p->_age = 20; //直接访问
return 0;
}
2、@private:修饰的实例变量只能在当前类的对象方法中直接访问 (在@implementation中定义的实例变量默认被@private修饰)
@interface Person : NSObject
{
@private
int _height;
}
- (void)test1;
- (void)setHeight:(int)height;
- (int)height;
@end
@implementation Person
{
int _no; //默认@private
}
- (void)test1
{
_height = 10; //直接访问
}
- (void)setHeight:(int)height
{
_height = height; //直接访问
}
- (int)height
{
return _height; //直接访问
}
@end
int main()
{
Person *p = [Person new];
//p->_height = 170; 不能直接访问
[p setHeight:170]; //调用set方法访问
p.height = 170; //点语法
//p->_no = 1; 不能直接访问
return 0;
}
3、@protected:修饰的实例变量能在当前类和子类的对象方法中直接访问 (在@interface中定义的实例变量默认被@protected修饰)#import <Foundation/Foundation.h>
@interface Person : NSObject
{
int _weight; //默认是@protected
}
- (void)test;
@end
@implementation Person
- (void)test
{
_weight = 50; //直接访问
}
@end
@interface Student : Person
- (void)study;
@end
@implementation Student
- (void)study
{
_weight = 50; //直接访问
}
@end
int main()
{
Person *p = [Person new];
//p->_weight = 100; 不能直接访问
return 0;
}
4、@package:只要处在同一个框架中,就能直接访问对象中被修饰的实例变量二、使用注意
1、@intercace中和@implementation中的实例变量不能同名,如果同名的话,它们的作用域有冲突,所以不能同名。
2、在@implementation中定义的实例变量就算用@public修饰,也是无效的,它还是在当前类的对象方法中才可以直接访问。
第二部分 关键字@property和@synthesize
一、@property和@synthesize
1、@property 可以自动生成某个实例变量的set方法和get方法的声明。
@property int age
// 转换成
- (void)setAge:(int)age;
- (int)age;
2、@synthesize生成
注意:如果是"@synthesize age;",默认会访问age这个成员量,如果没有age,就是自动生成@private类型的age
@synthesize age = _age;
// 转换成
- (void)setAge:(int)age
{
_age = age;
}
- (int)age
{
return _age;
}
二、新版本中的@property
@interface Person : NSObject
@property int age;
@end
@implementation Person
@end
1、在Xcode4.4之后,@property代替了@property和@synthesize的作用。2、@property int age;实现的3个功能
(1)自动生成了实例变量_age,但是_age的作用域是@private的。
(2)生成实例变量_age的get和set方法的声明
(3)生成实例变量_age的set和get方法的实现
3、使用注意
(1)如果手动在@interface和@end中定义了_age实例变量,那么_age就是@protected的,编译器就只会生成_age的set和get方法。
(2)如果手动实现了set方法,那么编译器就只会生成get方法和实例变量(3)如果手动实现了get方法,那么编译器就只会生成set方法和实例变量
(4)如果手动实现了set方法和get方法,那么编译器不会生成实例变量