一、黑马程序员self访问成员变量
程序示例:
#import <Foundation/Foundation.h>
interface Person : NSObject
{
int _age;
}
- (void)setAge: (int)age;
- (int)age;
- (void)test;
@end
@implementation Person
- (void)setAge: (int)age
{
_age = age;
}
- (int)age
{
// return _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;
}
二、黑马程序员self调用方法
程序示例:
/*
self的用途:
1.概念:指向当前类、对象(类方法、对象方法调用者);谁调用了当前方法,self就代表谁;
* self出现在对象方法中,self就代表对象
* self出现在类方法中,self就代表类
2.在对象方法中可以利用"self->成员变量名"访问当前对象内部的成员变量;
3.[self 方法名]调用当前类、对象的方法;
*/
#import <Foundation/Foundation.h>
@interface Dog : NSObject
- (void)bark;
- (void)run;
@end
@implementation Dog
- (void)bark
{
NSLog (@"汪汪汪");
}
- (void)run
{
[self bark];
NSLog (@"跑跑跑");
}
@end
int main()
{
Dog *d = [Dog new];
[d run];
return 0;
}
三、黑马程序员self使用注意
#import <Foundation/Foundation.h>
@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
{
// [self haha3]; 错误写法;函数不可以这样调用.
// [self haha1]; 错误写法
}
@end
int main()
{
[Person haha2];
[Person test2];
Person *p = [Person new];
[p test1];
return 0;
}