我想要能够做一些事情
MyType *the_thing = [[MyType alloc] init];Nsstring *the_dump = [the_thing dump]; //pseudo codeNSLog("Dumped Contents: %@",the_dump);
并显示对象的实例变量名称和值以及可在运行时调用的任何方法。理想地在一个易于阅读的格式。
对于熟悉PHP的开发人员,我基本上寻找等效的反射函数(var_dump(),get_class_methods())和OO Reflection API。
解决方法 更新:任何想要做这种东西的人可能想查看 Mike Ash’s ObjC wrapper for the Objective-C runtime。这或多或少是你怎么去的:
#import <objc/runtime.h>. . . -(voID)dumpInfo{ Class clazz = [self class]; u_int count; Ivar* ivars = class_copyIvarList(clazz,&count); NSMutableArray* ivararray = [NSMutableArray arrayWithCapacity:count]; for (int i = 0; i < count ; i++) { const char* ivarname = ivar_getname(ivars[i]); [ivararray addobject:[Nsstring stringWithCString:ivarname enCoding:NSUTF8StringEnCoding]]; } free(ivars); objc_property_t* propertIEs = class_copyPropertyList(clazz,&count); NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count]; for (int i = 0; i < count ; i++) { const char* propertyname = property_getname(propertIEs[i]); [propertyArray addobject:[Nsstring stringWithCString:propertyname enCoding:NSUTF8StringEnCoding]]; } free(propertIEs); Method* methods = class_copyMethodList(clazz,&count); NSMutableArray* methodArray = [NSMutableArray arrayWithCapacity:count]; for (int i = 0; i < count ; i++) { SEL selector = method_getname(methods[i]); const char* methodname = sel_getname(selector); [methodArray addobject:[Nsstring stringWithCString:methodname enCoding:NSUTF8StringEnCoding]]; } free(methods); NSDictionary* classDump = [NSDictionary dictionaryWithObjectsAndKeys: ivararray,@"ivars",propertyArray,@"propertIEs",methodArray,@"methods",nil]; NSLog(@"%@",classDump);}
从那里,很容易得到一个实例的属性的实际值,但你必须检查它们是否是原始类型或对象,所以我太懒了放在它。你也可以选择扫描继承链获取对象上定义的所有属性。然后,有类别上定义的方法,更多…但几乎一切都很容易获得。
这里是上面的代码转储UILabel的摘录:
{ ivars = ( "_size","_text","_color","_highlightedcolor","_shadowcolor","_Font","_shadowOffset","_minFontSize","_actualFontSize","_numberOflines","_lastlineBaseline","_linespacing","_textLabelFlags" ); methods = ( rawSize,"setRawSize:","drawContentsInRect:","textRectForBounds:","textSizeforWIDth:",. . . ); propertIEs = ( text,Font,textcolor,shadowcolor,shadowOffset,textAlignment,lineBreakMode,highlightedTextcolor,highlighted,enabled,numberOflines,adjustsFontSizetoFitWIDth,minimumFontSize,baselineAdjustment,linespacing,userInteractionEnabled );}总结
以上是内存溢出为你收集整理的objective-c – Objective C内省/反思全部内容,希望文章能够帮你解决objective-c – Objective C内省/反思所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)