通过分配新的 NSNumber 来更改 NSNumber 值?
我知道 NSNumber 是不可变的,但我仍然需要在我的应用程序中更改它。我使用它是因为它是一个对象,因此可以与 @property 一起使用(如果可以的话,我会立即使用 float 或 CGFloat,但遗憾的是,我不能)。
有什么方法可以覆盖旧的 NSNumber 实例吗?我正在尝试这样做:
NSNumber *zero = [[NSNumber alloc] initWithFloat:0.0];
myNSNumber = zero
但这不会改变该值。这是我的代码的简化版本,因为我正在更改根视图控制器的参数(我知道,不适合 MVC)。不过,值的改变应该是相同的赋值,对吧?我应该先释放 myNSNumber 吗?我应该为 myNSNumber 设置什么@property?
谢谢!
I understand that NSNumber is immutable, but I still have the need to change it in my app. I use it because it's an object, and therefore usable with @property (if I could, I would use float or CGFloat in a heartbeat, but sadly, I can't).
Is there any way to just overwrite the old NSNumber instance? I'm trying this:
NSNumber *zero = [[NSNumber alloc] initWithFloat:0.0];
myNSNumber = zero
but this doesn't change the value. This is a simplified version of my code, as I'm changing the root view controller's parameter (I know, not MVC-friendly). Still, the changing of the value should be the same assignment, right? Should I release myNSNumber first? What should I set the @property at for myNSNumber?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用诸如
numberWithDouble:
或numberWithInteger:
之类的便捷方法来获取 NSNumber 的自动释放实例。无需调用 alloc/init,特别是当您使用retain
说明符分配给属性时(这些在分配时自动保留/释放)。You can get an autoreleased instance of NSNumber using convenience methods such as
numberWithDouble:
ornumberWithInteger:
. No need to invoke alloc/init, especially if you're assigning to a property with theretain
specifier (these automatically retain/release upon assignment).((myViewController*)self.parentViewController).otherViewController.value
Psychic 调试告诉我,该属性链中的对象之一为零。我的钱花在了parentViewController上,因为我经常忘记设置父属性。
((myViewController*)self.parentViewController).otherViewController.value
Psychic debugging tells me that one of the objects in this chain of properties is nil. My money is on parentViewController because I often forget to set parent properties.