[Objective-C] isKindOfClass 和 class 方法

参考:

https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/index.html#//apple_ref/occ/intfm/NSObject/isKindOfClass:


Objc 中,isKindOfClass 方法原型如下。输入 Class 类型参数,返回 BOOL 类型值

- (BOOL)isKindOfClass:(Class)aClass


示例代码如下:

// ===== Person.h =====

@interface Person: NSObject
@end

// ===== Student.h =====

#import "Person.h"

@interface Student: Person
@end

// ===== main.m =====

#import "Person.h"
#import "Student.h"

int main(int argc, const char * argv[]) {
	@autoreleasepool {
		Student* s = [[Student alloc] init];
		NSLog(@"%hhd", [s isKindOfClass:[Student class]]);
		NSLog(@"%hhd", [s isKindOfClass:[Person class]]);
		NSLog(@"%hhd", [s isKindOfClass:@"Student"]);
		NSLog(@"%hhd", [s isKindOfClass:[NSString class]]);
		NSLog(@"%@", [Student class]);
		NSLog(@"%hhd", [Student isKindOfClass:[Person class]]);
	}
	return 0;
}

运行结果:

> 1
> 1
> 0
> 0
> Student
> 0

说明:

1) 下面函数原型中的”Class“相当于是一种 Object 类型,虽然上面代码中的 NSLog(@"%@", [Student class]); 打印出”Student“,但 Student class 返回的并不是 NSString,而是 Class 类型的object

- (BOOL)isKindOfClass:(Class)aClass

2) 像下面这样对 isKindOfClass 直接传入字符串,不能正确判断一个对象是否是该字符串对应类或其子类的对象

[s isKindOfClass:@"Student"];
3) [ Student isKindOfClass:[Person class]] 并没有像我们想象的那样返回1,而是返回0。然而,[ s isKindOfClass:[Person class]] 是返回1的。


你可能感兴趣的:([Objective-C] isKindOfClass 和 class 方法)