开发者

Creating a random fact app

I am he开发者_如何学运维lping my friend to develop a random fact app for iPhone which will be specific to certain areas of study.

My question is what is the best way to have say 100 or so facts and randomly generate them. I have a working prototype at the moment, but that just cycles through the facts using a NSMutableArray and an if loop.

What is the best way to randomize them so that every time the app is launched a different sequence appears? Should I be using a SQLite database?


You could shuffle the array, save its state, and the position in the array. That way every time you opened the app, it would be a new fact, and you could shuffle when all the facts have been seen, so that way you have to see every fact at least once before you see any fact a second time.

Then you could save the facts in multiple files, named the area you want. So maybe, you have a Science file, a History file, etc. Then the facts would only show the facts specific to the category.

I disagree with the SQLite DB implementation because that has a lot of maintenance unless you save the file on a server and get the db info with some kind of refresh functionality.

To shuffle the array, add a category to your class for NSMutableArray in your header file

@interface NSMutableArray (Shuffle)
-(void)shuffle;
@end

In your implementation file, add the category and the code:

@implementation NSMutableArray (Shuffle)
-(void)shuffle {

   for(int pivot = 0; pivot < [self count]; pivot++) {
       int index = arc4random() % [self count];

       [self exchangeObjectAtIndex:pivot withObjectAtIndex:index];
   }
}
@end

To save your array, and its location:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:arrayOfFacts forKey:@"Array"] //arrayOfFacts is the array that has the facts in it
[defaults setInteger:arrayPosition forKey:@"Array Position"]; //arrayPosition is the fact number you are on

Then, in your viewDidLoad, or where ever you are loading your objects, load from the NSUserDefaults:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
arrayPosition = [defaults integerForKey:@"Array Position"];
arrayOfFacts = [defaults stringArrayForKey:@"Array"];


Put your strings in SQLite, yes.

Then the query you want is:

SELECT * FROM table ORDER BY RANDOM() LIMIT 1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜