41

iOS·NSObject的两种含义:类与协议

 5 years ago
source link: http://www.cocoachina.com/ios/20180918/24946.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1. 区分:类的NSObject与协议的NSObject

iOS开发中,苹果提供的一些系统类都属于NSObject的子类,例如UIColor类的定义如下所示。

fQv6juV.png!webUIColor

或者自定义的类,也继承自NSObject,例如下图所示。

EviUf2E.png!web自定义类的父类

但是,NSObject不仅仅代表基类,还有协议的意思,我们可以称之根协议,例如下图所示:

VRJRJ3r.png!webNSObject协议

事实上,从NSObject类的定义可知,NSObject的类本身就遵循NSObject协议,如下图所示。

JnAVjq3.png!webNSObject

2. 协议NSObject的用法

  • NSObject协议的定义

MJVZn2A.png!webimage.png

  • 普通协议的用法

@protocol MyProtocol
- (void)foo; 
@end
  • 继承根协议的用法

@protocol MyProtocol
<nsobject>
  
- (void)foo; 
@end
</nsobject>
  • 多继承的用法

假设你自定义一个继承自UITextField的子类MyTextFeild,同时自定义一个代理MyTextFeildDelegate的属性如下:

@protocol MyTextFieldDelegate 
<nsobject>
 
//...

@property (nonatomic, weak) id 
 <mytextfeilddelegate>
   delegate;
 </mytextfeilddelegate>
</nsobject>

这时候会报错的,因为这个delegate与父类的delegate的协议冲突。一个解决办法是利用协议的多继承:将自定义的协议继承自父类中的协议。

@protocol MyTextFieldDelegate 
<nsobject uitextfielddelegate="">
 

//...
@property (nonatomic, weak) id 
 <mytextfeilddelegate>
   delegate;
 </mytextfeilddelegate>
</nsobject>

3. 拓展

OC里面的类本来是不支持多继承的,但有的面试官还是会问到iOS里面如何实现多继承?除了运行时的办法,还有一种就是通过协议的多继承来实现。

作者:陈满iOS

链接:https://www.jianshu.com/p/1ba089d69c73


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK