/*
self的用途:
1> 谁调用了当前方法,self就代表谁
* self出现在对象方法中,self就代表对象
* self出现在类方法中,self就代表类
2> 在对象方法利用"self->成员变量名"访问当前对象内部的成员变量
2> [self 方法名]可以调用其他对象方法\类方法
*/
@interface Dog : NSObject
- (void)bark;
- (void)run;
@end
@implementation Dog
- (void)bark
{
NSLog(@"汪汪汪");
}
- (void)run
{
[self bark];
//NSLog(@"汪汪汪");
NSLog(@"跑跑跑");
}
@end
int main()
{
Dog *d = [Dog new];
[d run];
return 0;
}
@interface Person : NSObject
{
int _age;
}
- (void)setAge:(int)age;
- (int)age;
- (void)test;
@end
@implementation Person
- (void)setAge:(int)age
{
// _age = age;
self->_age = age;
}
- (int)age
{
return self->_age;
}
- (void)test
{
// self:指向了方向调用者,代表着当期对象
int _age = 20;
NSLog(@"Person的年龄是%d岁", self->_age);
}
@end
int main()
{
Person *p = [Person new];
[p setAge:10];
[p test];
return 0;
}
@interface Person : NSObject
- (void)test;
+ (void)test;
- (void)test1;
+ (void)test2;
- (void)haha1;
+ (void)haha2;
@end
@implementation Person
- (void)test
{
NSLog(@"调用了-test方法");
// 会引发死循环
//[self test];
}
+ (void)test
{
NSLog(@"调用了+test方法");
// 会引发死循环
//[self test];
}
- (void)test1
{
[self test]; // -test
}
+ (void)test2
{
[self test]; // +test
}
- (void)haha1
{
NSLog(@"haha1-----");
}
void haha3()
{
}
+ (void)haha2
{
// haha3();
[self haha3];
// [self haha1];
}
@end
int main()
{
[Person haha2];
//Person *p = [Person new];
//[p test1];
return 0;
}
原文地址:http://blog.csdn.net/wangzi11322/article/details/45112467