【发布时间】:2013-01-14 21:10:13
【问题描述】:
由于名为“age”的属性也总是有一个名为“age”的选择器,我可以使用respondsToSelector 作为question suggests,它会告诉我在运行时是否存在特定的选择器在任何给定的对象中。
如果存在名为“age”的属性,我可以验证。我怎么知道该选择器(该属性的读取方法)是返回对象(id)还是非对象(int)?
这种类型确定是否可以在运行时进行,或者是 Objective-C 方法总是假设某人使用我希望它使用的类型实现了该方法,或者我也可以验证返回类型?
这是在 XCode 4.5 中使用最新的 Objective-C 版本 (LLVM 4.1)。
更新:这是我提出的实用程序类别 NSObject:
- (NSString*) propertyType: (NSString*)propname
{
objc_property_t aproperty = class_getProperty([self class], [propname cStringUsingEncoding:NSASCIIStringEncoding] ); // how to get a specific one by name.
if (aproperty)
{
char * property_type_attribute = property_copyAttributeValue(aproperty, "T");
NSString *result = [NSString stringWithUTF8String:property_type_attribute];
free(property_type_attribute);
return result;
}
else
return nil;
}
在研究这个问题时,我还编写了这个方便实用的实用方法 可以列出这个对象的所有属性:
- (NSArray*) properties;
{
NSMutableArray *results = [NSMutableArray array];
@autoreleasepool {
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList([self class], &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char * aname=property_getName(property);
[results addObject:[NSString stringWithUTF8String:aname]];
//const char * attr= property_getAttributes(property);
//[results addObject:[NSString stringWithUTF8String:attr]];
}
if (properties) {
free(properties);
}
} // end of autorelease pool.
return results;
}
【问题讨论】:
-
我认为你需要添加 if (properties) free(properties);到你得心应手的类别实用方法
-
可能是对的。几个月来我没有做过任何 Objective-C 编码,感觉很生疏。我也不是 100% 确定你是对的。 :-) 我可能需要一些 Objective-C 运行时阅读才能弄清楚。
-
在做同样的事情之前,我已经编写了自己的类别,并且还必须自己解决这个问题。只是在看到 Carl 的回答提到 free() 使用 property_copyAttributeValue 之后才注意到它现在更仔细地查看文档
-
好的,我相信你的话。请您进行代码编辑(编辑我的帖子),如果您的代表太低,我会批准它
-
感谢您的编辑,DonnaLea!
标签: objective-c introspection dynamic-typing