OC里Self的应用

来源:互联网 发布:MAC maven安装配置 编辑:程序博客网 时间:2024/05/21 07:01

一、 Self:相当于java里的this指针

1.应用场景:
1)用在类方法里
2)用在对象方法里
3)访问成员变量
4)Self在OC的内存管理特殊使用

2.在对象方法里的使用:指定的是当前对象
1)我们先创建一个Person类,里面有两个方法不带参数的run 与带参数的eat 方法
然后调用run 方法

@interface Person :NSObject}-(void) run;-(void) eat:(NSString *) footName;@end@implementation Person-(void) run{    @NSLog(@"somebody is running");}-(void) eat:(NSString *) footName{    @NSLog(@"somebody is eatting", footName);    //在此使用self    [self run];}@end

2)在主类里使用Person类
首先的引入头文件,然后在主函数里创建对象,调用eat方法就能实现调用run方法

#import "person.h"int main(int argc, const char * argv[]){    @autoreleasepool {                Person *p = [Person new];        [p eat];    }    return 0;}

3.在类方法里的使用:指定的是当前类
1)我们先创建一个Person类,里面有两个方法不带参数的walk与带参数的take方法
然后调用walk方法

@interface Person :NSObject}+(void)walk;+(void)take:(NSString*) footName;@end@implementation Person+(void)walk{    NSLog(@"somebody is walking");}+(void)take:(NSString*) footName{    NSLog(@"somebody is taking %@", footName);    [self walk];}@end

2)在主类里使用Person类
首先的引入头文件,然后在主函数里创建对象,调用eat方法就能实现调用run方法

#import "person.h"int main(int argc, const char * argv[]){    @autoreleasepool {         [Person take];        Person p= [Person new];        //打印类的地址  结果是两种都相同        NSLog(@"Person = %p",[Person class]);        NSLog(@"Person = %p",[p class]);    }    return 0;}

4.Self修饰变量
1)我们先创建一个Person类,创建set与get方法

@interface Person : NSObject{    @public    int _weight;}-(void) setWeight:(int) weight;-(int) getWeight;@end@implementation Person//在此处使用self-(void) setWeight:(int) weight{    self->_weight = weight;}-(int) getWeight{    return self->_weight;}@end

2)在主类里使用Person类

#import "person.h"int main(int argc, const char * argv[]){    @autoreleasepool {             Person p= [Person new];        [p setWeight:50];        int weight = [p getWeight];        NSLog(@"weight = %d",weight);    }    return 0;}

5.总结:
谁调用self就代表谁

0 0
原创粉丝点击