我需要跟踪数组中的整数值,有时我需要修改数组中的值。
现在我这样做:
// 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/