self 调用方法小结
用途:
1.概念:指向了当前对象(方法调用着) 谁调用指向谁
2.可以用“self—>成员变量名”访问当前对象内部的成员变量
3.[self 方法名]可以调用其他对象方法/类方法
例子1 谁调用指向谁
#import <Foundation/Foundation.h>
@interface Dog : NSObject
- (void)bark;
- (void)run;
@end
@implementation Dog
- (void)bark
{
NSLog(@"汪汪");
}
- (void)run
{
[self brak];//等同于后面的 //NSLog(@"汪汪");
//NSLog(@"汪汪");
NSLog(@"跑跑");
}
@end
int main()
{
Dog *d = [Dog new];
[d run];
return 0;
}
/*例子 2,可以用“self—>成员变量名”访问当前对象内部的成员变量
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
int age;
int weight;
}
- (void)setAge:(int)age;
- (int)age;
-(void)test
@end
@implementation Person
- (void)setAge:(int)age
{
_age = age;
}
-(int)age
{
return _age;
}
-(void)test
{
//int age1 = _age;
int _age = 20;
//self的作用相当于这一句int age1 = _age;//谁调用指谁
NSLog(@"person年龄%d岁",self->_age); //self-> _age 相当于p-> _age
}
@end
int main()
{
Person *p = [Person new]
[p setage:10];// p-> _age = 10;
[p test];
return 0;
}
*/
例子3.[self 方法名]可以调用其他对象方法/类方法
#import <Foundation/Foundation.h>
@interface JiSuanQi : NSObject
+ (int)sumOfNum1:(int)num1 andNum2:(int)num2;
+ (int)averageOfNum1:(int)num1 andNum2: (int)num2;
@end
@implementation JiSuanQi
+ (int)sumOfNum1:(int)num1 andNum2:(int)num2
{
return 0;
}
+ (int)averageOfNum1:(int)num1 andNum2: (int)num2
{
//这时 self代表类
int a = [self sumOfNum1: num1 andNum2:num2];//等同于下面一句
//int a = [JiSuanQi sumOfNum1: num1 andNum2:num2];
return sum / 2;
}
@end
int main()
{
int a = [JiSuanQi sumOfNum1:10 andNum2:12]
NSLog(@"a = %d", a);
return 0;
}
|
|