main.m文件
#import
#import "Student.h"
#import "Person.h"
#pragma mark NSObject常用方法
void objUse() {
Student *stu = [[[Studentalloc] init]autorelease];
// isKindOfClass判斷對象是否屬於某個類或者 子類
if ( [stu isKindOfClass:[Personclass]] ) {
// NSLog(@"stu屬於Person或者繼承自Person");
}
// isMemberOfClass判斷對象是否屬於某個類(不包括子類)
BOOL result = [stu isMemberOfClass:[Student class]];
// NSLog(@"%i", result);
// 直接調用
// [stu test];
// 間接調用
[stuperformSelector:@selector(test)];
// [stu performSelector:@selector(test2:) withObject:@"abc"];
// 延遲2秒後調用test2:方法
[stu performSelector:@selector(test2:)withObject:@"abc"afterDelay:2];
}
void reflect() {
// 類的反射
NSString *str = @"Person";
Class class = NSClassFromString(str);
Person *person = [[class alloc] init];
NSLog(@"%@", person);
// Class變成字符串
NSString *name = NSStringFromClass([Personclass]);
// 方法的反射
NSString *method = @"test";
SEL selector = NSSelectorFromString(method);
[personperformSelector:selector];
// 將SEL轉換為字符串
NSString *selectorName = NSStringFromSelector(selector);
[personrelease];
}
int main(int argc,const char * argv[])
{
@autoreleasepool {
reflect();
}
return 0;
}
Person.h文件
#import
@interface Person :NSObject
- (void)test;
@end
Person.m文件
#import "Person.h"
@implementation Person
- (void)test {
NSLog(@"調用了Person的test方法");
}
@end
Student.h文件
#import "Person.h"
@interface Student :Person
- (void)test;
- (void)test2:(NSString *)a;
@end
Student.m文件
#import "Student.h"
@implementation Student
- (void)test {
NSLog(@"調用了test方法");
}
- (void)test2:(NSString *)a {
NSLog(@"調用了test2方法:%@", a);
}
@end