由于名为“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;
}
最佳答案
您可以使用class_copyPropertyList
来获取类中声明的属性列表。
Describes the properties declared by a class.
然后property_getAttributes
:
property_getAttributes
Returns the attribute string of an property.
Here您可以找到一些更具体的提示和示例。
作为旁注,以下声明:
Since property named "age" would always have a selector named "age" as well
不正确,因为属性可以有自定义 getter 和/或 setter:
@property (nonatomic, getter=isImmediate) BOOL immediate;
编辑:
我在another S.O. post中找到的一些示例代码:
const char * type = property_getAttributes(class_getProperty([self class], "myPropertyName"));
NSString * typeString = [NSString stringWithUTF8String:type];
NSArray * attributes = [typeString components separatedByString:@","];
NSString * typeAttribute = [attributes objectAtIndex:0];
NSString * propertyType = [typeAttribute substringFromIndex:1];
const char * rawPropertyType = [propertyType UTF8String];
if (strcmp(rawPropertyType, @encode(float)) == 0) {
//it's a float
} else if (strcmp(rawPropertyType, @encode(int)) == 0) {
//it's an int
} else if (strcmp(rawPropertyType, @encode(id)) == 0) {
//it's some sort of object
} else ....
关于objective-c - 如何在运行时检查特定属性及其返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14326711/