NSObject和反射

如何NSObject和反射


NSObject 常用方法

如何判断 某个对象是否属于某个类或子类

-(BOOL)isKindOfClass:(Class)aClass

判断是否为aClass的实例(不包括aClass的子类)

-(BOOl)isMemberOfClass:(Class)aClass

判断是否实现了aProtocol协议

-(BOOL)conformToProtocol:(Protocol)aProtocol

判断这个类的对象是否拥有参数提供的方法

+(BOOL)instancesRespondToSelector:(SEL)aSelector

判断对象是否拥有参数提供的方法

-(BOOL)respondsToSelector:(SEL)aSelector

延迟调用参数提供的方法,方法所需参数用withobject 传入

-(void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay


//创建Person类

//继承Person的Student类

main.m

#import “Student.h”//enough

id stu=[[[Student alloc]init]autorelease];//Student *stu

//判断类型

//class 方法  返回一个指向结构体的指针

image

//the following code will judge this object of stu belong to the class of Student

if([stu isKindOfClass:[Student class]]) //Student can be replaced by Person

{

NSLog(@”stu belonged to Person or inherit from Person ”);

}

//only belong can’t inherit

BOOL result=[stu isMumberOfClass:[Student class]]; //Person –>no


//Student.h

@interface Student:Person

-(void)test;

-(void)test1:(int)a;

@end

Student.m

@implementation Student

-(void)test{

NSLog(@”call test”);

}

-(void)test1:(int)a{

NSLog(@”call test1,%i”,a);

}

@end

main.m

// call directly

[stu test];

[stu test1:10];

//indirect call

image

[stu performSelector:@selector(test:)];

[stu performSelector:@selector(test2:) withObject:];

//只能修改test2

test2:(NSString )str

//最多两个参数

[stu performSelector:@selector(test2:) withObject:@”abc”];

//performSelector在哪个线程调用,test2就在哪个线程

//延迟调用

[stu performSelector:@selector(test2:) withObject:@”abc” afterDelay:2];

//看不到效果,因为命令行项目这个函数一调用完,就是main的结尾,主程序关闭,定时器还有个屁用


反射:根据字符串来实例化一个对象

image

void reflect(){

NSString *str=@”Person”;

Class class=NSClassFromString(str);

//实例化

Person *person=[[class alloc]init];

NSLog(@”%@”,person);

[person release];

}

原文地址:https://www.cnblogs.com/yesihoang/p/4555147.html