Hi.
I am new to iphone development. I am "old School" - I was tought to use Procedures etc. when programming. Everything is object oriented these days but my style is still as its always been. Please bear that in mind. My project is tiny and really just a proof of concept.
The program below works on a timer - every 30 seconds it will read a random baby name from my list of names database stored in Dictionary.plist by my app. It then shows this name on the iphone screen.
You can see the full relevant parts of the code below. What happens is - if I increase the timer to run it very fast - eventually it seems to run out of memory or something as it just shows ???? instead of the next random baby name. I suspect this is due to me not closing the database file each time I read it.
Anyway, can someone please look at my code (with my above comments into consideration) and tell me what I need to add to stop it showing ???? after so many runs..
I am only opening the file each time in ShowNextName as I couldnt figure out another way to do it..
I know its not great style to use variables at the start of this code that are global etc. but is there maybe a way to restructure or add something to stop it "crashing" or going a bit funny after so many runs...
I'd appreciated that. Thanks.
#import "BabyNameViewController.h"
@implementation BabyNameViewController
NSDictionary *dictionary;
NSString *name;
int nameCount = 0;
int RecordIndex = 0;
- (void)ShowNextname;
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Dictionary.plist"];
NSArray* plistArray = [NSArray arrayWithContentsOfFile:finalPath];
// Generate a random number between 0 and (the number of records-1) - used as a random index!
RecordIndex=arc4random()%[plistArray count];
// Select and display currently selected record from the array.
dictionary = [plistArray objectAtIndex:RecordIndex];
name = [dictionary objectForKey:@"name"];
[nameLabelOutlet setText: [NSString stringWithFormat: @"Random Baby Name is: %@", name]];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
// Initial App entry point - startup code..
// Open the dictionary to count the number of names and store it for later use.
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Dictionary.plist"];
NSArray* plistArray = [NSArray arrayWithContentsOfFile:finalPath];
nameCount = [plistArray count];
// Generate random name from database
[self ShowNextname];
// Start up the nameUpdate timer.
[NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(nameUpdate) userInfo:nil repeats:YES];
}
-(void) nameUpdate {
[self ShowNextname];
}