【发布时间】:2014-02-21 17:41:08
【问题描述】:
我有一个声明两个属性的类。
@property (nonatomic, readonly, weak) id first;
@property (nonatomic, weak) id second;
我在运行时使用以下代码检查属性的属性:
unsigned int propertyCount;
objc_property_t *properties = class_copyPropertyList(class, &propertyCount);
for (int propertyIndex = 0; propertyIndex < propertyCount; propertyIndex++) {
objc_property_t property = properties[propertyIndex];
const char *rawName = property_getName(property);
NSString *propertyName = [NSString stringWithCString:rawName encoding:[NSString defaultCStringEncoding]];
BOOL isWeak = [self propertyIsWeak:property];
char const *attributes = property_getAttributes(property);
NSString *attributesString = [NSString stringWithCString:attributes encoding:[NSString defaultCStringEncoding]];
NSArray *attributesArray = [attributesString componentsSeparatedByString:@","];
BOOL weak = [attributesArray containsObject:@"W"];
NSLog(@"attributes of property are %@. Weak? %d", attributesString, weak);
}
不幸的是,我得到了这些结果:
attributes of property are T@,R,N,V_first. Weak? 0
attributes of property are T@,W,N,V_second. Weak? 1
从https://developer.apple.com/library/mac/documentation/cocoa/conceptual/objcruntimeguide/articles/ocrtpropertyintrospection.html 的文档中可以清楚地看出,第一个属性也应该有一个“W”,但它没有。有谁知道如何检测这个属性实际上很弱?
请注意,将它声明为弱确实很重要,编译器会关心并适当地对待它。
这似乎是一个错误,但我仍然需要一个真正有效的方法。
【问题讨论】:
-
出于好奇...为什么需要在运行时确定这一点?为什么能够检查这对您很重要?
-
我认为这里的W代表写,我的意思是读和写。不弱
-
@santhu 访问链接,您会看到 W 代表弱。 @MicahHainline 我猜这是在告诉您,也许您不能拥有只读且弱的属性。查看属性
first的程序集,看看有没有weak的代码有什么不同。 -
@Gavin,我正在编写需要在整个代码库中保持不变的东西的运行时验证。即某些类型的类不持有指向某些其他类的强指针。基本上是自动化测试。
-
听上去很蛋疼。
标签: ios iphone objective-c objective-c-runtime