我想使用Dictionary数组创建一个随机字符串。当用户运行应用程序时,我想生成随机问题。我使用数组完成了随机字符串。但我无法使用字典数组创建随机字符串。那么如何使用字典创建随机字符串。每次运行应用程序时都会更改字符串数组,那么如何生成随机字符串?
例如:
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;
})
感谢。
答案 0 :(得分:3)
一个非常简单的解决方案是创建一个临时数组,其中包含字典中的所有字符串。然后使用
int index = arc4random() % [tempArray count];
[randomArray addObject:[tempArray objectAtIndex:index]];
[tempArray removeObjectAtIndex:index];
然后重复这个直到你满意为止。
答案 1 :(得分:0)
我知道这个“技巧”。如果您使用plist文件,您可以像这样创建文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>firstStringKey</key>
<dict>
<key>something</key>
<string>foo</string>
</dict>
<key>secondStringKey</key>
<dict>
<key>something</key>
<string>foo</string>
</dict>
<key>thirdStringKey</key>
<dict>
<key>something</key>
<string>foo</string>
</dict>
</dict>
</plist>
之后当您重新加载文件时:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"List" ofType:@"plist"];
NSDictionary* allFile = [[NSDictionary alloc] initWithContentsOfFile:filePath];
NSArray* pointStrings = [allFile allKeys];
返回所有字典键但没有订单......也许你可以使用它。 NSDictionary documentation
答案 2 :(得分:0)
Pugal,
使用NSMutableArray代替NSArray,以便您可以使用更多方法进行访问,
NSUInteger count = [self count];
for (NSUInteger i = 0; i < count; ++i) {
// Select a random element between i and end of array to swap with.
int nElements = count - i;
int n = (random() % nElements) + i;
[self exchangeObjectAtIndex:i withObjectAtIndex:n];
}
检查链接以获取进一步参考:What's the Best Way to Shuffle an NSMutableArray? 约翰逊已经很好地解释了它。