self关键字
作用1
例:
#import <Foundation/Foundation.h> @interface People : NSObject
{
int _age;
} - (void)setAge:(int)age;
- (int)age; @end @implementation People - (void)setAge:(int)age
{
_age = age;
} - (int)age
{
int _age = 10;
return self->_age;
} @end int main()
{
People *p = [People new];
[p setAge:26];
int age = [p age];
NSLog(@"年龄为:%d",age);
return 0;
}
作用2
例
#import <Foundation/Foundation.h> @interface People : NSObject
- (void)fun1;
- (void)fun2;
@end @implementation People - (void)fun1
{
NSLog(@"执行了第一个方法");
[self fun2];
} - (void)fun2
{
NSLog(@"执行了第二个方法");
} @end int main()
{
People *p = [People new];
[p fun1];
return 0;
}
作用3
例
#import <Foundation/Foundation.h> @interface People : NSObject
+ (void)fun1;
+ (void)fun2;
@end @implementation People + (void)fun1
{
NSLog(@"执行了第一个类方法");
[self fun2];
} + (void)fun2
{
NSLog(@"执行了第二个类方法");
} @end int main()
{
[People fun1];
return 0;
}