isKindOfClass,isMemberOfClassの違い
2720 ワード
この2つの方法はよく私たちを困惑させますが、どんな違いがありますか?
まず、それらの定義を見てみましょう.
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.isMemberOfClass:
公式解釈:Returns a Boolean value that indicates whether the receiver is an instance of a given class.
NSObjectに引き継がれたPerson,PersonのTeacherの2つのクラスがある
isKindOfClassを使用する例:
出力結果:
isMemberOfClassを使用する例:
出力結果:
この二つの例を見れば分かるはずだ.
定義#テイギ#
まず、それらの定義を見てみましょう.
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.isMemberOfClass:
公式解釈:Returns a Boolean value that indicates whether the receiver is an instance of a given class.
使用
の使用については、ネット上でイメージ的な例を見て、ここで直接使ってみました.NSObjectに引き継がれたPerson,PersonのTeacherの2つのクラスがある
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
NSString *name;
}
-(void)setName:(NSString*)n;
@end
#import "Person.h"
@implementation Person
-(void)setName:(NSString *)n
{
name = n;
}
@end
#import "Person.h"
@interface Teacher : Person
-(void)teach;
@end
#import "Teacher.h"
@implementation Teacher
-(void)teach
{
NSLog(@" ");
}
@end
isKindOfClassを使用する例:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Person *person = [[Person alloc] init];
Teacher *teacher = [[Teacher alloc] init];
//YES
if ([teacher isKindOfClass:[Teacher class]]) {
NSLog(@"teacher Teacher Teacher ");
}
//YES
if ([teacher isKindOfClass:[Person class]]) {
NSLog(@"teacher Person Person ");
}
//YES
if ([teacher isKindOfClass:[NSObject class]]) {
NSLog(@"teacher NSObject NSObject ");
}
[person release];
[teacher release];
[pool release];
出力結果:
2012-07-04 14:34:17.315 ObjectiveCTest[2595:f803] teacher Teacher Teacher
2012-07-04 14:34:17.316 ObjectiveCTest[2595:f803] teacher Person Person
2012-07-04 14:34:17.316 ObjectiveCTest[2595:f803] teacher NSObject NSObject
isMemberOfClassを使用する例:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Person *person = [[Person alloc] init];
Teacher *teacher = [[Teacher alloc] init];
//YES
if ([teacher isMemberOfClass:[Teacher class]]) {
NSLog(@"teacher Teacher ");
}
//NO
if ([teacher isMemberOfClass:[Person class]]) {
NSLog(@"teacher Person ");
}
//NO
if ([teacher isMemberOfClass:[NSObject class]]) {
NSLog(@"teacher NSObject ");
}
[person release];
[teacher release];
[pool release];
出力結果:
2012-07-04 14:23:07.965 ObjectiveCTest[2460:f803] teacher Teacher
この二つの例を見れば分かるはずだ.