To use a SQLite3 database in your application, you first need to add the libsqlite3.dylib library to your Xcode project. The following Try It Out demonstrates how. You will need to download the code files indicated for this exercise and the rest of the Try It Out features in this chapter.
TRY IT OUT: Preparing Your Project to Use SQLite3
#import <UIKit/UIKit.h> #import “sqlite3.h” @interface DatabasesViewController : UIViewController { sqlite3 *db; } -(NSString *) filePath; -(void) openDB; -(void) createTableNamed:(NSString *) tableName withField1:(NSString *) field1 withField2:(NSString *) field2; -(void) insertRecordIntoTableNamed:(NSString *) tableName withField1:(NSString *) field1 field1Value:(NSString *) field1Value andField2:(NSString *) field2 field2Value:(NSString *) field2Value; -(void) getAllRowsFromTableNamed: (NSString *) tableName; @end
#import “DatabasesViewController.h” @implementation DatabasesViewController -(NSString *) filePath { NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [paths objectAtIndex:0]; return [documentsDir stringByAppendingPathComponent:@“database.sql”]; }
How It Works
In order to work with SQLite3, you must link your application to a dynamic library called libsqlite3.dylib. The libsqlite3.dylib that you selected is an alias to the latest version of the SQLite3 library. On an actual iPhone device, the libsqlite3.dylib is located in the /usr/lib/ directory.
To use a SQLite database, you need to create an object of type sqlite3:
sqlite3 *db;
The filePath method returns the full path to the SQLite database that will be created in the Documents directory on your iPhone (within your application's sandbox):
-(NSString *) filePath { NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [paths objectAtIndex:0]; return [documentsDir stringByAppendingPathComponent:@“database.sql”];
NOTE Chapter 10 discusses the various folders that you can access within your application's sandbox.
18.217.7.117