• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Yesi-悦思
"(program(computers) == *art) ? so : what" 修身岂为名传世,作事惟思利及人
博客园    首页    新随笔    联系   管理    订阅  订阅

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];

}

posted @ 2015-06-05 17:17  悦思  阅读(208)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3