如何在 Objective-C 中设置 NSNumber 变量的值(不创建新对象)
如何在 Objective-C 中设置 NSNumber 变量的值(不创建新对象)?
背景
- 我正在使用 Core Data 并有一个托管对象,该对象具有 NSNumber (动态属性),
- 将其传递(通过引用)到另一个方法,该方法将更新它,
- 不确定如何更新它?如果我分配另一个新的 NSNumber 事情不起作用,我想这是有道理的,然后它会得到一个指向不同对象的指针,而不是核心数据对象(我猜)
how do I set the value of an NSNumber variable (without creating a new object) in objective-c?
Background
- I'm using Core Data and have a managed object that has an NSNumber (dynamic property)
- passing (by reference) this to another method which will update it
- not sure how to update it? if I allocate it another new NSNumber things don't work, which I guess makes sense it's then got a pointer to a different object not the core data object (I guess)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NSNumber 对象是不可变的。这意味着更改包含 NSNumber 的属性的唯一方法是为其指定一个新的 NSNumber。要执行您想要的操作,您有
以下三个选项: 1. 将 Core Data 对象传递给该方法并让它直接设置属性。
调用方式为
[self updateNumberOf:theCoreDataObject];
2. 让 update 方法返回一个新的 NSNumber 并在调用者中更新它。
调用使用:
3.传递一个指向数字变量的指针并在调用者中更新它(如果您需要返回其他内容,我只会建议在选项 2 上这样做)。
称为使用:
在这些示例中,我没有考虑内存管理。确保正确释放/自动释放对象。
4.(来自 Greg 的评论)与选项 1 类似,但将密钥传递给 update 方法以更加便携。
调用方式为
[self updateNumberOf:theCoreDataObject forKey:@"number"];
An NSNumber object isn't mutable. This means that the only way to change a property containing a NSNumber is to give it a new NSNumber. To do what you want, you have three options:
1. Pass the Core Data object to the method and have it directly set the property.
Called as
[self updateNumberOf:theCoreDataObject];
2. Have the update method return a new NSNumber and update it in the caller.
Called using:
3. Pass a pointer to a number variable and update it in the caller (I would only suggest this over option 2 if you need to return something else).
Called using:
I did not bother with memory management in any of these examples. Make sure you release/autorelease objects appropriately.
4. (from Greg's comment) Similar to option 1, but passes the key to the update method to be more portable.
Called as
[self updateNumberOf:theCoreDataObject forKey:@"number"];