gogoWebsite

IOS Data Storage

Updated to 2 days ago
  • //  
  • //    
  • //  Persistence3  
  • //  
  • //  Created by liu lavy on 11-10-3.  
  • //  Copyright 2011 __MyCompanyName__. All rights reserved.  
  • //  
  •   
  • #import ""  
  • #import <>  
  •   
  • @implementation Persistence3ViewController  
  • @synthesize field1;  
  • @synthesize field2;  
  • @synthesize field3;  
  • @synthesize field4;  
  •   
  • //The complete path to the data file  
  • - (NSString *)dataFilePath {  
  •     //Retrieve the Documents directory path. The second parameter means limiting search to our application sandbox  
  •     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  •     // Each application has only one Documents directory  
  •     NSString *documentsDirectory = [paths objectAtIndex:0];  
  •     //Create a file name  
  •     return [documentsDirectory stringByAppendingPathComponent:kFilename];  
  • }  
  •   
  • // When the application exits, save the data to the attribute list file  
  • - (void)applicationWillResignActive:(NSNotification *)notification {  
  •     sqlite3 *database;  
  •     if(sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK) {  
  •         sqlite3_close(database);  
  •         NSAssert(0, @"Failed to open database");  
  •     }  
  •       
  •     for(int i = 1; i <= 4; i++) {  
  •         NSString *fieldname = [[NSString alloc] initWithFormat:@"field%d", i];  
  •         UITextField *field = [self valueForKey:fieldname];  
  •         [fieldname release];  
  •           
  •         char *update = "INSERT OR REPLACE INTO FIELDS (ROW, FIELD_DATA) VALUES (?, ?);";  
  •         sqlite3_stmt *stmt;  
  •         //Compile the SQL statement into a structure (sqlite3_stmt) inside sqlite, similar to the PreparedStatement precompilation of java JDBC  
  •         if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == SQLITE_OK) {  
  •             //When binding parameter, the index of the parameter list starts from 1, and when taking out data, the index of the column starts from 0  
  •             sqlite3_bind_int(stmt, 1, i);  
  •             sqlite3_bind_text(stmt, 2, [ UTF8String], -1, NULL);  
  •         } else {  
  •             NSAssert(0, @"Error:Failed to prepare statemen");  
  •         }  
  •         //Execute SQL text to get the results  
  •         int result = sqlite3_step(stmt);  
  •         if(result != SQLITE_DONE) {  
  •             NSAssert1(0, @"Error updating table: %d", result);  
  •         }  
  •         //Release the memory occupied by stmt (allocated by sqlite3_prepare_v2())  
  •         sqlite3_finalize(stmt);  
  •     }  
  •     sqlite3_close(database);  
  • }  
  •   
  • /* 
  •  // The designated initializer. Override to perform setup that is required before the view is loaded. 
  •  - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
  •  self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
  •  if (self) { 
  •  // Custom initialization 
  •  } 
  •  return self; 
  •  } 
  •  */  
  •   
  • /* 
  •  // Implement loadView to create a view hierarchy programmatically, without using a nib. 
  •  - (void)loadView { 
  •  } 
  •  */  
  •   
  •   
  •   
  • // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  
  • - (void)viewDidLoad {  
  •     [super viewDidLoad];  
  •     NSString *filePath = [self dataFilePath];  
  •     //Check whether the data file exists  
  •     if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {  
  •         //Open the database  
  •         sqlite3 *database;  
  •         if(sqlite3_open([filePath UTF8String], &database) != SQLITE_OK) {  
  •             sqlite3_close(database);  
  •             NSAssert(0, @"Failed to open database");  
  •         }  
  •           
  •         //Create a table  
  •         char *errorMsg;  
  •         NSString *createSQL =   
  •             @"CREATE TABLE IF NOT EXISTS FIELDS (ROW INTEGER PRIMARY KEY, FIELD_DATA TEXT);";  
  •         if(sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK) {  
  •             sqlite3_close(database);  
  •             NSAssert(0, @"Error creating table: %s", errorMsg);  
  •         }  
  •   
  •         //Inquiry  
  •         NSString *query = @"SELECT ROW, FIELD_DATA FROM FIELDS ORDER BY ROW";  
  •         sqlite3_stmt *statement;  
  •         //Set nByte to speed up operation  
  •         if(sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {  
  •             while (sqlite3_step(statement) == SQLITE_ROW) {//Return to each row  
  •                 int row = sqlite3_column_int(statement, 0);  
  •                 char *rowData = (char *)sqlite3_column_text(statement, 1);  
  •                   
  •                 NSString *fieldName = [[NSString alloc] initWithFormat:@"field%d", row];  
  •                 NSString *fieldValue = [[NSString alloc] initWithUTF8String:rowData];  
  •                   
  •                 UITextField *field = [self valueForKey:fieldName];  
  •                  = fieldValue;  
  •                   
  •                 [fieldName release];  
  •                 [fieldValue release];  
  •             }  
  •             //Release the memory occupied by the statement (allocated by sqlite3_prepare())  
  •             sqlite3_finalize(statement);  
  •         }  
  •         sqlite3_close(database);  
  •     }  
  •       
  •       
  •     UIApplication *app = [UIApplication sharedApplication];  
  •     [[NSNotificationCenter defaultCenter] addObserver:self  
  •                                              selector:@selector(applicationWillResignActive:)  
  •                                                  name:UIApplicationWillResignActiveNotification  
  •                                                object:app];  
  •     [super viewDidLoad];  
  • }  
  •   
  •   
  • /* 
  •  // Override to allow orientations other than the default portrait orientation. 
  •  - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
  •  // Return YES for supported orientations 
  •  return (interfaceOrientation == UIInterfaceOrientationPortrait); 
  •  } 
  •  */  
  •   
  • - (void)didReceiveMemoryWarning {  
  •     // Releases the view if it doesn't have a superview.  
  •     [super didReceiveMemoryWarning];  
  •       
  •     // Release any cached data, images, etc that aren't in use.  
  • }  
  •   
  • - (void)viewDidUnload {  
  •     self.field1 = nil;  
  •     self.field2 = nil;  
  •     self.field3 = nil;  
  •     self.field4 = nil;  
  •     [super viewDidUnload];  
  • }  
  •   
  •   
  • - (void)dealloc {  
  •     [field1 release];  
  •     [field2 release];  
  •     [field3 release];  
  •     [field4 release];  
  •     [super dealloc];  
  • }  
  •   
  • @end