ios Objective c 将字符串对象添加到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13629632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:22:21  来源:igfitidea点击:

Objective c add string object to an array

iphoneobjective-ciosarraysipad

提问by Imme22009

I've looked everywhere for this, online, on stack overflow and cannot still work out what I'm doing wrong.

我到处寻找这个,在线,堆栈溢出,但仍然无法弄清楚我做错了什么。

I'm trying to add an element to an existing NSMutableArray. But it crashes on line 4:

我正在尝试向现有的 NSMutableArray 添加一个元素。但它在第 4 行崩溃:

-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x897b320

The code:

编码:

NSMutableArray *mystr = [[NSMutableArray alloc] init];

mystr = [NSArray arrayWithObjects:@"hello",@"world",@"etc",nil];

NSString *obj = @"hiagain";

[mystr addObject:obj];

What am I doing wrong? This is driving me crazy!!!

我究竟做错了什么?这真让我抓狂!!!

回答by giorashc

You array is not mutable!. Use NSMutableArray

你的数组是不可变的!。用NSMutableArray

mystr = [NSMutableArray arrayWithObjects:@"hello",@"world",@"etc",nil];

You get unrecognized selectorsince NSArraydoes not contain the addObjectmethod

你得到 无法识别的选择器,因为NSArray它不包含addObject方法

回答by rmaddy

Your code should be:

你的代码应该是:

NSMutableArray *mystr = [[NSMutableArray alloc] initWithObjects:@"hello",@"world",@"etc",nil];

NSString *obj = @"hiagain";

[mystr addObject:obj];

回答by Eimantas

The second line you're reassigning an instance of NSArrayrather of NSMutableArrayto your mystrvariable.

第二行你重新分配的一个实例NSArray宁可NSMutableArray给你的mystr变量。

Try something like this:

尝试这样的事情:

NSMutableArray *mystr = [NSMutableArray  arrayWithObjects:@"hello",@"world",@"etc",nil];

[mystr addObject:@"hiagain"]

回答by Robert Zahm

You originally create mystr as a mutable array, but then assign it to a standard NSArray in the next line. Instead of calling "arrayWithObjects," add each item using "addObjects" or some other function that doesn't create a new immutable array.

您最初将 mystr 创建为可变数组,但随后将其分配给下一行中的标准 NSArray。不是调用“arrayWithObjects”,而是使用“addObjects”或其他一些不会创建新的不可变数组的函数来添加每个项目。

回答by Imme22009

Ahhhhh spotted it already

啊啊啊已经发现了

Line 2 should be:

第 2 行应该是:

[NSMutableArray arrayWithObjects:@"hello",@"world",@"etc",nil];

Sorry to waste your time with that!

抱歉浪费你的时间!