【问题标题】:Get reference to the NSObject in an NSValue在 NSValue 中获取对 NSObject 的引用
【发布时间】:2016-05-12 06:49:31
【问题描述】:

我有一个NSMutableDictionary,其中包含UIImageView 对象和UIView 键。

当我将UIImageView 设置为NSMutableDictionary 时,我从UIView 中得到NSValue,如下所示:

[viewImageMap setObject:anImage forKey:[NSValue valueWithNonretainedObject:aView]];

我想知道我是否可以通过NSValue 对象获取UIView 引用。像这样的:

UIView *aView = (UIView *)[NSObject objectWithValue:aValue];

【问题讨论】:

标签: objective-c cocoa cocoa-touch nsvalue


【解决方案1】:

对于每个valueWith<Type>: 方法,NSValue 都有一个互补方法,该方法以适当的类型返回存储的值。

你需要的是nonRetainedObjectValue

UIView * theView = [theValue nonRetainedObjectValue];

【讨论】:

    【解决方案2】:

    这里是如何做到这一点:

    NSValue * myViewKey = [NSValue valueWithNonretainedObject:myView];
    UIView * myViewFromValue = (UIView*) myViewKey.nonretainedObjectValue
    

    【讨论】:

    • 这就是 OP 使用NSValue 的原因,它确实符合NSCopying
    • 当然,但我仍然认为这在架构方面不是一个好主意。
    • 谢谢!但是你能告诉我为什么这不是一个好主意吗?
    • 我刚刚编辑了我的答案并对此进行了解释。
    • NSValue保留;这就是 Nonretained 的意思。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    相关资源
    最近更新 更多