OC里Self的应用
发布日期:2021-06-30 22:37:23 浏览次数:2 分类:技术文章

本文共 1835 字,大约阅读时间需要 6 分钟。

一、 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就代表谁

转载地址:https://lovoo.blog.csdn.net/article/details/51525937 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android 关于ListView的一些小总结
下一篇:Android 实现简单媒体播放器功能

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月27日 17时58分57秒