I'm struggling with Models for database tables in Objective C.
The problem I'm having is that I appear to be repeating myself a lot in code; and I'm not sure if I am doing it right.
I have successfully setup FMDB to pull in a simple database. The database will allow you to add/edit/delete from 2 tables; "Teams" and "Players".
Okay, here's the breakdown.
EditorAppDelegate -->
here I init the FMDatabase, and do a quick test to make sure the database has been loaded; and I do a quick SELECT * FROM teams. Everything is fine.
RootViewController -->
This is just a menu where it says "Teams" and "Players".
TeamViewController -->
This is a TableViewController where it will eventually display the teams.
Now, what I want is to move the SELECT * FROM teams (and other SQL stuff) into its own model. This is considered best practice.
Okay. So I set up a model: TeamsModel.h and TeamsModel.m
I create a method called "getTableContents" where it does the simple SELECT * command from my earlier tests.
Problem 1: FMDB cannot be found
It no longer see's FMDB anymore, even though I included it in my AppDelegate file, and its an AppDelegate variable.
It no longer see's FMResultSet; even though its included the AppDelegate file.
Problem 2: A lot of repetitive coding! UGH!
My current solution to problem 1 is just to include the AppDelegate and all the database files again.
IE:
Code:
#import "EditorAppDelegate.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
And then in my getTableContents method I do:
Code:
-(void)getTableContents
{
EditorAppDelegate *appDelegate = (EditorAppDelegate *)[[UIApplication sharedApplication] delegate];
FMResultSet *rs = [appDelegate.db executeQuery:@"SELECT * FROM Teams"];
if ([appDelegate.db hadError])
{
NSLog(@"Err %d: %@", [appDelegate.db lastErrorCode], [appDelegate.db lastErrorMessage]);
}
// some other processing would go here
}
I know this is wrong.
1. I'm including the App Delegate; but I need this because the AppDelegate has the "db", a pointer to FMDatabase.
2. I'm including the FMDatabase files more than once in the whole application!
What annoys me is that if I have another 6 odd tables doing add/edit/delete's for their respective tables I would need to keep including the relevant files over and over again.
I really hate repeating myself, and I know that you should not be including the App Delegate like I have above.
Therefore, I'm looking for the best practices when it comes to Model files for databases and how to reduce the amount of times I need to include files, etc.
If this isn't clear enough, please let me know.
Any help would be great.