My application’s main window shows a SplitViewController. On the left is a TableView that displays the names. On the right is a DetailsView consisting of 2 textviews that displays the name and age.
This is the SQLite database and ‘USERS’ table i have created for my application.
-(NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"Mydata.sqlite"];
}
- (void)viewDidLoad
{
[super viewDidLoad];
if(sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK)
{
sqlite3_close(database);
NSAssert(0, @"Failed to open database.");
}
char *err;
NSString *sql = @"CREATE TABLE IF NOT EXISTS USERS" "(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, AGE INTEGER);";
if(sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK)
{
sqlite3_close(database);
NSAssert(0, @"Failed to create table.");
}
}
I want to populate the TableView with the names. When a name is selected in the table, the textviews on the right side of the SplitViewController will display the selected name as well as the age.
May i know how to do this?
There are a number of questions in there. From the sounds of it you want to know how to load the values, how to display them in a tableview, how to send a message from the tableView to the mainview and then how to display the content in your main view.
First off create a model object for the ‘User’ object. Then in the user class write a static method that you can call that returns all the users in an array.
Once you have the array, use it to populate the tableView using the standard ‘cellForRowAtIndexPath’ method. Once the user taps on a cell, pass the selected user object over to the main view via a delegate method and then finally display its various details (name, age, etc) in your relevant labels that you will have in there.
If any of that is unclear let me know and I can post a code snippet to help you out.
EDIT: So.. code snippet for creating an object and loading it into the tableViewController (only writing the .ms):
For the User class
Now for your table View Controller:
Hopefully that gives you an idea of how to proceed. If you are confused about how to proceed I recommend that you read up on the ‘Model View Controller’ Programming methodology and how table views work. Its a bit of work to start off with but you’ll get there.
Hope that helps 🙂