gpt4 book ai didi

objective-c - 在NSArray中增加NSNumber

转载 作者:行者123 更新时间:2023-12-01 19:14:42 25 4
gpt4 key购买 nike

我看过this,但是需要一种比这更简单的方法。

如果我有一个NSNumbers数组,并且想要增加其中一个,我必须这样做吗?

[myMutableArray replaceObjectAtIndex:index withObject:[NSNumber numberWithInt:[(NSNumber *)[myMutableArray objectAtIndex:index] intValue] + 1]];

要么
myArray = [myArray.mutableCopy replaceObjectAtIndex:index withObject:[NSNumber numberWithInt:[(NSNumber *)[myArray objectAtIndex:index] intValue] + 1]].copy;

如果出于某种原因决定使用不可变数组。

我知道我总是可以使用int数组,但是我只是好奇是否有一种简单的方法来做到这一点。

另外,如果我需要在实现中或整个文件(整个.m)中访问它而不使其成为全局变量,那么该如何定义一个int数组呢?

将它简单地放在实现/文件的顶部会很简单吗?
static int *myInt;

最佳答案

正如其他人所说,是的,您需要执行许多步骤。使用文字,阅读起来会更容易一些:

myMutableArray[index] = @( [ myMutableArray[index] intValue] + 1 ) ;

您的第二个代码示例不起作用,因为 replaceObjectAtIndex:withObject:返回 void,而不是它所作用的NSMutableArray。您需要先创建NSArray的 mutableCopy,然后创建 replaceObject,然后将NSArray设置为NSMutableArray的 copy

关于objective-c - 在NSArray中增加NSNumber,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14075643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com