Objective-C类方法中使用self注意事项

一、在类方法中使用self作为参数,需要特别注意。
使用self,实际上是Class类型,并不是我们期望的类对象。

例如下边代码会报错:

@interface RequestItem : NSObject
-(instancetype)initWithOwner:(ViewController*)delegate;
-(instancetype)initWithOwnerTwo:(id)delegate;
@end

@implementation ViewController
/*
 incompatible pointer types sending 'Class' to parameter of type 'ViewController'
编译器提示开发者:把Class当做ViewController使用了
*/
+(void)gotoInfoClassTwo{
    NSLog(@"第二种情况:在类方法中使用self作为参数,参数是self的类型");
    RequestItem  __unused *requestItem = [[RequestItem alloc]initWithOwner:self];

}
@end
二、在类(或实例)方法中使用self调用方法(如果是错误的使用,编译器会给出编译错误)。
1.实例方法中
  • self【可以】调用实例方法(最常见),实例方法里面的self,是对象的首地址。
  • self【不可以】调用类方法,此时self不是Class。【编译错误】No visible @interface for ‘xx’ declares the selector ‘xx’
2.类方法中
  • 类方法中,self【可以】调用类方法,此时self是Class。
  • 类方法中,self【不可以】调用实例方法。【编译错误】 No known class method for selector ‘xxxxx’。
3.注意:
  • self跟着函数的本质不同,也会不同。所以,在类方法中使用self,就要特别注意了。

原文:
Objective-C类方法中使用self注意事项
代码例子:
测试代码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值