如何在 iPhone 中使用 NSArray 创建随机字符串?
我想使用字典数组创建随机字符串。我想在用户运行应用程序时生成随机问题。我已经使用数组完成了随机字符串。但我无法使用字典数组创建随机字符串。那么如何使用字典创建随机字符串。每次运行应用程序时,字符串数组都会发生变化,那么如何生成随机字符串呢?
例如:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"List" ofType:@"plist"];
NSArray* pointStrings = [[NSArray alloc] initWithContentsOfFile:filePath];
我的实际数组是,
The array is (
{
id = 1;
question = India;
answer = Punjab;
},
{
id = 2;
question = Kolkatta;
answer = "West Bengal";
},
{
id = 3;
question = Mumbai;
answer = Maharastra;
} )
预期数组,
随机数组(
{
id = 2;
question = Kolkatta;
answer = "West Bengal";
},
{
id = 3;
question = Mumbai;
answer = Maharastra;
},
id = 1;
question = India;
answer = Punjab;
})
谢谢。
I want to create a random strings using array of Dictionary. I want to generate the random questions, when user runs the application. I had done with the random strings using arrays. But i couldn't create random strings using array of dictionary. So how to create a random strings using dictionary. The array of strings would be changed every time, when runs the application, so how can i generate random strings?
For eg:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"List" ofType:@"plist"];
NSArray* pointStrings = [[NSArray alloc] initWithContentsOfFile:filePath];
My actual array is,
The array is (
{
id = 1;
question = India;
answer = Punjab;
},
{
id = 2;
question = Kolkatta;
answer = "West Bengal";
},
{
id = 3;
question = Mumbai;
answer = Maharastra;
} )
Expected array,
The Random array(
{
id = 2;
question = Kolkatta;
answer = "West Bengal";
},
{
id = 3;
question = Mumbai;
answer = Maharastra;
},
id = 1;
question = India;
answer = Punjab;
})
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个非常简单的解决方案是使用字典中的所有字符串创建一个临时数组。然后使用
然后重复此操作,直到您满意为止。
A very simple solution is to create a temporary array with all the strings you have in your dictionary. Then use
And then repeat this until you are satisfied.
Pugal,
使用NSMutableArray代替NSArray,这样可以有更多的方法来访问,
NSUInteger count = [self count];
检查链接以获取更多参考: What's the Best Way to Shuffle an NSMutableArray?
约翰逊在里面已经解释得很清楚了。
Pugal,
Use NSMutableArray instead of NSArray so that you can have more methods to access,
NSUInteger count = [self count];
Check the link for further reference: What's the Best Way to Shuffle an NSMutableArray?
Johnson has already explained well in it.
我知道一个“技巧”。如果您使用 plist 文件,您可以像这样创建文件:
之后,当您像这样重新加载文件时:
返回所有字典键,但没有顺序......也许您可以使用这个。 NSDictionary 文档
I know a "trick" for that. If you use a plist file you can create your file like this :
After that when you reload your file like this :
That return all dictionary keys but without order… Maybe you can use this. NSDictionary documentation