randomly choose from plist [duplicate]
Possible Duplicate:
create random integers for quiz using plist
Using xcode, how do I randomly choose from my plist? I have created 84 questions in my plist and want to randomly choose 10 to create a quiz when user clicks button.
So far I have
NSString *plistFile = [[NSBundle mainBundle] pathForResource:@"global" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsofFile:plistFile];
NSLog(@"%@",[dict objectForKey:@"1"]);
NSLog(@"%@",[dict objectForKey:@"2"]);
NSLog(@"%@",[dict objectForKey开发者_运维百科:@"3"]);
Global is the plist name, @"1", @"2", etc are the names for each different question. This is my long way of creating a quiz with random questions.
Have you checked this. Then, you need to have your own algorithm to keep it unique 10 numbers.
If your keys really are @"1"
, @"2"
, etc, then you can just choose a random number and select that object. For example,
int i = (arc4random() % 84) + 1;
[dict objectForKey:[NSString stringWithFormat:@"%d",i]];
However, in this case it seems to me that you should instead have an NSArray
of questions instead of an NSDictionary
. Then you could simply do
int i = arc4random() % 84;
[questionArray objectAtIndex:i];
To get 10
distinct random numbers chosen from 84
possibilities, the easiest is probably just to keep an NSMutableArray
of the numbers. Then, generate another random number as above and before adding it to the array, check that it isn't already there. For example:
NSMutableArray *questionNumbers = [[NSMutableArray alloc] init];
int i;
while ([questionNumbers count] < 10) {
i = arc4random() % 84;
if (![questionNumbers containsObject:[NSNumber numberWithInt:i]]) {
[questionNumbers addObject:[NSNumber numberWithInt:i]];
}
}
Don't forget to release questionNumbers
at some point if you choose this approach.
You can use a solution to another question to accomplish this:
What's the Best Way to Shuffle an NSMutableArray?
Using the -shuffle
method from that solution, you can do the following:
- (NSArray *)getRandomObjectsFromDictionary:(NSDictionary *)dict numObjects:(NSInteger)numObjects
{
NSMutableArray *keys = [[[dict allKeys] mutableCopy] autorelease];
[keys shuffle];
numObjects = MIN(numObjects, [keys count]);
NSMutableArray randomObjects = [NSMutableArray arrayWithCapacity:numObjects];
for (int i = 0; i < numObjects; i++) {
[randomObjects addObject:[dict objectForKey:[keys objectAtIndex:i]]];
}
return [NSArray arrayWithArray:randomObjects];
}
This will work for any NSDictionary
, regardless of what the keys are.
精彩评论