I want to load tableView values from a database, called for test purposes database.sqlite.
It is populated with the following:
1, January
2, February
… down to …
12, December
As you will see I’m using FMDB. The following line compiles but crashes:
NSString *myString = [[rows objectAtIndex:myNumber] objectForKey:@"MonthName"];
I’m having problems coming to terms with the inconsistent way you deal with Ints and String in Cocoa which is part of my problem. Also, although there are NSLog debugging lines in there this approach looks convoluted. What advice can you give me?
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:@"database.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
[database open];
NSLog(@"Open Database");
FMResultSet *results = [database executeQuery:@"SELECT * FROM monthly"];
while([results next]) {
NSString *name = [results stringForColumn:@"name"];
NSInteger age = [results intForColumn:@"age"];
// Stuff Data into Array
NSMutableArray *rows = [[NSMutableArray alloc] init];
NSMutableDictionary *firstRow = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:age], @"MonthID", [NSString stringWithFormat:@"%@", name], @"MonthName", nil];
[rows addObject:firstRow];
NSLog(@"Month: %@ - %d",name, age);
int myNumber = [[firstRow objectForKey:@"MonthID"] intValue];
// *** THE LINE BELOW IS GIVING ME PROBLEMS ***
NSString *myString = [[rows objectAtIndex:myNumber] objectForKey:@"MonthName"];
// NSLog(@"Month No: %@ - %d",myString, myNumber);
NSLog(@"***** Month No: %d", myNumber);
// [self.monthMonths myString];
}
[database close];
NSLog(@"Close Database");
This line gives error because your index or month id is starting from 1 but when you add it in array:
it gets added at 0 index(default starting index).
So when you call this line:
it tries to extract value at index 1 because:
It actually tries to extract value at index 1 which is not present because your array contain only 1 value at index 0 so it crashes.
Edit:Try using this: