objective-c 如何在Objective c中为iphone创建一个字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1602572/
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
How to create an Array of Strings in Objective c for iphone
提问by Chris Barry
I'm trying to create an array of strings that can be randomized and limited to a certain x number of strings.
我正在尝试创建一个字符串数组,这些字符串可以随机化并限制为特定的 x 个字符串。
If the array could be randomized I could pick the first x strings and that would work fine.
如果数组可以随机化,我可以选择第一个 x 字符串,这样就可以了。
I'm trying to use code like this currently
我目前正在尝试使用这样的代码
NSString *statements[9];
statements[0] = @"hello";
This seems to work but the array seems to be full of rubbish data.
这似乎有效,但数组似乎充满了垃圾数据。
Can someone help me in the right direction. (is the memory allocation being done in the wrong way?
有人可以帮助我朝着正确的方向前进。(内存分配是否以错误的方式进行?
Thanks
谢谢
回答by Justin Gallagher
Do you want an array with nine strings in it?
你想要一个包含九个字符串的数组吗?
[NSArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", nil]
回答by Johnny Oshika
As of Xcode 4.4, you can use Array Literals, which are much cleaner and easier to read. You no longer need to include 'nil'. For example:
从 Xcode 4.4 开始,您可以使用 Array Literals,它更清晰、更易于阅读。您不再需要包含“nil”。例如:
NSArray *myArray = @[@"1", @"2", @"3", @"4", @"5"];
回答by Chuck
All C auto arrays like that will be full of garbage until you fill them. As long as it isn't getting filled with garbage later, everything is working as expected. However, Cocoa includes the NSArray class which is more common to use for arrays of objects (since it does proper memory management and works with the rest of the framework and all that).
像这样的所有 C 自动数组都将充满垃圾,直到您填满它们。只要它以后没有被垃圾填满,一切都会按预期进行。然而,Cocoa 包含 NSArray 类,它更常用于对象数组(因为它进行适当的内存管理并与框架的其余部分以及所有这些一起工作)。
回答by NSResponder
Just a tip, it's not necessary to shuffle the contents of the array. Just randomize the access. For each card you want to pick from the deck, pick a random number and select the card at that index. Then, take the top card and place it where the card you just picked was.
只是一个提示,没有必要打乱数组的内容。只是随机化访问。对于您要从牌组中挑选的每张卡片,请选择一个随机数并选择该索引处的卡片。然后,取出最上面的卡片并将其放在您刚刚选择的卡片所在的位置。
If you reallywant to sort the array though, you can do it with very little code using -sortedArrayUsingSelector:where your comparison method returns NSOrderedAscendingor NSOrderedDescendingrandomly.
如果你真的想对数组进行排序,你可以使用很少的代码来完成 -sortedArrayUsingSelector:你的比较方法返回NSOrderedAscending或NSOrderedDescending随机返回。

