API文檔
- isKindOfClass
Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class. (required)
- isMemberOfClass
Returns a Boolean value that indicates whether the receiver is an instance of a given class. (required)
異同點
相同點
都是NSObject的比較Class的方法
不同點
1. isKindOfClass來確定一個對象是否是一個類的成員,或者是派生自該類的成員
2. isMemberOfClass只能確定一個對象是否是當(dāng)前類的成員
即isMemberOfClass不能檢測任何的類都是基于NSObject類這一事實,而isKindOfClass可以
[[NSMutableData data] isKindOfClass:[NSData class]]; // YES
[[NSMutableData data] isMemberOfClass:[NSData class]]; // NO
例:
- (void)testIsKindOfClass {
Class1 *c1=[[Class1 alloc] init];
if ([c1 isKindOfClass: [NSObject class]]) {
NSLog(@"c1 is a kind of NSObject.");
}
if ([c1 isMemberOfClass:[Class1 class]]) {
NSLog(@"c1 is Member of Class1 !");
}
if (![c1 isMemberOfClass:[NSObject class]]) {
NSLog(@"c1 is't Member of NSObject !");
}
}
輸出結(jié)果:
c1 is a kind of NSObject .
c1 is Member of Class1 !
c1 is't Member of NSObject !
特殊情況
蘋果官方文檔有這樣一段描述
Be careful when using this method on objects represented by a class cluster. Because of the nature of class clusters, the object you get back may not always be the type you expected. If you call a method that returns a class cluster, the exact type returned by the method is the best indicator of what you can do with that object. For example, if a method returns a pointer to an NSArray object, you should not use this method to see if the array is mutable, as shown in the following code:
// DO NOT DO THIS!
if ([myArray isKindOfClass:[NSMutableArray class]]) {
// Modify the object
}
If you use such constructs in your code, you might think it is alright to modify an object that in reality should not be modified. Doing so might then create problems for other code that expected the object to remain unchanged.
If the receiver is a class object, this method returns YES if aClass is a Class object of the same type, NO otherwise.
測試如下
NSArray *myArr = [[NSArray alloc] init];
NSMutableArray *myArr2 = [[NSMutableArray alloc] init];
if ([myArr isKindOfClass:[NSArray class]]) {
NSlog(@"myArr isKindOfClass of NSArray");
}
if ([myArr isMemberOfClass:[NSArray class]]) {
NSlog(@"myArr isMemberOfClass of NSArray");
}
if ([myArr2 isKindOfClass:[NSMutableArray class]]) {
NSlog(@"myArr2 isKindOfClass of NSMutableArray");
}
if ([myArr2 isMemberOfClass:[NSMutableArray class]]) {
NSlog(@"myArr2 isMemberOfClass of NSMutableArray");
}
輸出結(jié)果:
myArr isKindOfClass of NSArray
myArr2 isKindOfClass of NSMutableArray
- 總結(jié)如下
- NSArray、NSMutableArray屬于類簇,使用isMemberOfClass不能得到正確的結(jié)果
原因:由于類簇的性質(zhì),這類對象實際返回的實例有不確定性 - NSArray對象可能會在運行時發(fā)現(xiàn)其實運作的是NSCFArray(來自Core Foundation框架(C語言的實現(xiàn)版本),很多Cocoa對象都是如此做橋接的)
- 對于類簇的判斷要謹(jǐn)慎