在iOS开发中,会遇到需要判断一个对象是否为某类的对象、是否能响应方法等,通过源码我们可以看一下它们区别是什么呢?
实现源码:
Class object_getClass(id obj)
{
if (obj) return obj->getIsa();
else return Nil;
}
+ (Class)class {
return self;
}
- (Class)class {
return object_getClass(self);
}
+ (BOOL)isMemberOfClass:(Class)cls {
return object_getClass((id)self) == cls;
}
- (BOOL)isMemberOfClass:(Class)cls {
return [self class] == cls;
}
+ (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
- (BOOL)isKindOfClass:(Class)cls {
for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
+ (BOOL)instancesRespondToSelector:(SEL)sel {
if (!sel) return NO;
return class_respondsToSelector(self, sel);
}
+ (BOOL)respondsToSelector:(SEL)sel {
if (!sel) return NO;
return class_respondsToSelector_inst(object_getClass(self), sel, self);
}
- (BOOL)respondsToSelector:(SEL)sel {
if (!sel) return NO;
return class_respondsToSelector_inst([self class], sel, self);
}
由源码我们可以分析出:
- + (Class)class 和- (Class)class 均返回类本身
- + (BOOL)isMemberOfClass: 是判断该类的元类是否和class相等
- - (BOOL)isMemberOfClass: 判断该类是和class相等
- + (BOOL)isKindOfClass: 循环遍历该类的元类的父类,判断是否和class相等
- - (BOOL)isKindOfClass: 循环遍历该类的父类,判断是否和class相等
- + (BOOL)instancesRespondToSelector 该类是否能响应实例方法
- + (BOOL)respondsToSelector: 该类是能否响应类方法
- - (BOOL)respondsToSelector: 该对象是否能响应实例方法
网友评论