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

标签 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 的文档中可以清楚地看出第一个属性也应该有一个“W”,但它没有。有谁知道如何检测这个属性实际上很弱?

请注意,它被声明为弱确实很重要,编译器会关心并适本地对待它。

这看起来像是一个错误,但我仍然需要一个真正有效的方法。

最佳答案

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

我会在 .h 中将其设置为只读,然后如果您希望它成为 .m 文件中的弱变量,则有

@property (nonatomic, weak) id first

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

关于ios - 如何在运行时确定只读属性是否弱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21941418/

相关文章:

iphone - 从文档文件到 NSData

ios - RealmSwiftObject 不受 Realm 管理。获取带有返回类的对象

css - 用于隐藏浏览器 chrome 的 JavaScript 导致位置 : fixed bug on iOS

ios - Game Center 的持久数据?

iphone - 在 xcode 4.4 中使用类扩展

javascript - 有更好的 Android 支持的 JQTouch 的 JQuery 替代品吗?

ios - Google Sign In iOS SDK - Carthage 支持

ios - 使用 UIBezierPath 的圆角半径

objective-c - 在 Objective-C 中确定屏幕位置 (NSScreen)

objective-c - 用于 iPhone 开发的 GameMaker