【问题标题】:How can I determine at runtime if a read-only property is weak?如何在运行时确定只读属性是否弱?
【发布时间】: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


【解决方案1】:

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

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

@property (nonatomic, weak) id first

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

【讨论】:

  • 我对属性应该声明为什么不感兴趣。我只对检测它是什么感兴趣。
  • 为什么?即通过确定它试图实现什么?我最初的观点是你不会声明只读的东西,弱。因此,通过这样做,您会混淆问题,因此您会得到意想不到的结果。毕竟它指向的实例必须在某个地方很强大才能存在。
  • 我试图通过确定某些代码中的不变量的运行时验证来实现单元测试目的。人们正在创建(只读的、弱的)属性,它确实会改变应用程序的运行时行为,当它们弱与不弱时。
  • 人们将事物标记为只读的事实,如果由于上述原因而不是您应该如何做,弱是有趣的。我会修复代码,问谁在写它 WTF?并且不用担心测试坏代码 IMO
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多