如何在运行时确定只读属性是否较弱?

时间:2014-02-21 17:41:08

标签: ios iphone objective-c objective-c-runtime

我有一个声明两个属性的类。

@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的文档中,第一个属性应该有一个&#39; W&#39;还有,但它没有。有谁知道如何检测到这个属性实际上很弱?

请注意,它被声明为弱,确实很重要,编译器会对其进行适当的处​​理和处理。

这似乎是一个错误,但我仍然需要一种实际可行的方法。

1 个答案:

答案 0 :(得分:1)

通过将其设置为只读意味着您不会创建一个setter方法。所以把它设置为弱,是反直觉的。除了更改合成的ivar的生命周期限定符之外,强/弱修饰符对readonly属性没有任何影响

我会在.h中将其设置为Readonly然后如果你想让它成为.m文件中的弱变量

@property (nonatomic, weak) id first

这样,如果你想要它,它只是外部的,但内部是弱的。