objective-c - 在这种情况下使用 CFMutableArrayRef 是否更明智?

标签 objective-c c arrays

我需要跟踪数组中的整数值,有时我需要修改数组中的值。

现在我这样做:

// Read an integer from the array
NSNumber* num = [NSNumber numberWithInteger:someInteger];
[numArray addObject:num];

更新值:

// Update an integer in the array
NSNumber* num = [numArray lastObject]; // get old
NSInteger numInt = [numInt integerValue]; // convert
NSNumber* newNum = [NSNumber numberWithInteger:numInt + someAddition]; // create new
[numArray removeLastObject]; // remove old
[numArray addObject:newNum]; // set new

这太糟糕了。涉及这么多对象,都是因为 NSNumber 是不可变的。现在我想也许我必须转向古老的 C 语言并使用 CFMutableArrayRef?我可以在其中存储简单的 NSInteger 值而不需要所有这些开销吗?

最佳答案

您可以使用replaceObjectAtIndex: withObject: 命令:

[numArray replaceObjectAtIndex:[array count]-1 withObject:newNum];

比你的方法好

关于objective-c - 在这种情况下使用 CFMutableArrayRef 是否更明智?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5819038/

相关文章:

c - 不确定如何解析参数并利用 excevp 函数

javascript - 使用字符串中的键/值对创建对象?

Javascript OOP 和数组

如果无法使用 NSURLSession 下载文件,iOS::error 为零

c - Fgets 错误 段错误

objective-c - 如何在 xcode 中创建数组键和值?

c - 使用 fscanf 读取输入文件在中线失败

c - C 中的字符串文字以 %?

ios - 在后台每 X 分钟执行一次函数不起作用

ios - 初始化时出现 Firebase 错误 'NSInvalidArgumentException'