【问题标题】:How to deep copy int in obj-c如何在 obj-c 中深度复制 int
【发布时间】:2017-04-15 13:29:56
【问题描述】:

作为一名自学成才的程序员,我最近开始了解在使用单例数组和字典时进行深/浅复制。今天我发现了另一个问题,那就是即使是 int 值也需要深度复制(?)。让我来说明问题:

[[MyData singleton] car].id = -10;
int carId = [[MyData singleton] car].id;
carId = abs(carId);
NSLog(@"%d", carId);

Log says

-10.

I would expect it to be 10 but no. 

那么我该如何深度复制这个值呢?我试过了

int newCarId = abs(carId);

但仍然无法正常工作。帮助。

【问题讨论】:

  • int 是原始的。它总是按值复制/传递
  • 我就是这么想的。也许我还缺少其他东西。
  • ideone.com/RLVA48 打印 10。
  • 好的,找出问题所在。与深度复制无关。问题是超出范围的问题,它给了我一个负数。将类型更改为 long long 可以解决问题。无论如何感谢您的帮助。

标签: ios objective-c int deep-copy


【解决方案1】:

我创建了一个测试APP来测试它但是不能再次出现你的问题,我的代码:

@interface DingTest : NSObject

@property (nonatomic, assign) int testValue;

@end

@implementation DingTest @end

@interface AppDelegate () @end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

DingTest *testClass = [[DingTest alloc]init];
testClass.testValue = -2;

int b = testClass.testValue;
b = abs(testClass.testValue);
NSLog(@"%d", testClass.testValue);
NSLog(@"%d", b);
NSLog(@"%d", abs(testClass.testValue));
NSLog(@"%d", abs(b));

return YES;

}

我的日志: -2 2 2 2

你可以复制粘贴来测试一下

您是否使用了 'assign' 或其他关键字?

【讨论】:

  • 我赞成这个,因为你努力帮助我。原来问题是由于其他原因(超出范围问题)。谢谢。
猜你喜欢
  • 1970-01-01
  • 2013-12-03
  • 1970-01-01
  • 2015-02-28
  • 1970-01-01
  • 2018-10-08
  • 2011-07-25
  • 1970-01-01
  • 2017-04-09
相关资源
最近更新 更多