IOS data storage includes the following storage mechanisms:
- Property List
- Object Archive
- SQLite3
- CoreData
- AppSettings
- Normal file storage
1. Attribute list
Copy the codeThe code is as follows:
//
//
// Persistence1
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/>
#define kFilename @""
@interface Persistence1ViewController : UIViewController {
UITextField *filed1;
UITextField *field2;
UITextField *field3;
UITextField *field4;
}
@property (nonatomic, retain) IBOutlet UITextField *field1;
@property (nonatomic, retain) IBOutlet UITextField *field2;
@property (nonatomic, retain) IBOutlet UITextField *field3;
@property (nonatomic, retain) IBOutlet UITextField *field4;
- (NSString *)dataFilePath;
- (void)applicationWillResignActive:(NSNotification *)notification;
@end
Copy the codeThe code is as follows:
//
//
// Persistence1
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import ""
@implementation Persistence1ViewController
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
//The complete path of the data file
- (NSString *)dataFilePath {
//Retrieve the Documents directory path. The second parameter indicates that search is restricted to our application sandbox
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//Each application has only one Documents directory
NSString *documentsDirectory = [paths objectAtIndex:0];
//Create file name
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
// When the application exits, save the data to the attribute list file.
- (void)applicationWillResignActive:(NSNotification *)notification {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject: ];
[array addObject: ];
[array addObject: ];
[array addObject: ];
[array writeToFile:[self dataFilePath] atomically:YES];
[array release];
}
/*
// 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]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
= [array objectAtIndex:0];
= [array objectAtIndex:1];
= [array objectAtIndex:2];
= [array objectAtIndex:3];
[array release];
}
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
2. Object Archive
Copy the codeThe code is as follows:
//
//
// Persistence2
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Foundation/>
@interface Fourlines : NSObject <NSCoding, NSCopying> {
NSString *field1;
NSString *field2;
NSString *field3;
NSString *field4;
}
@property (nonatomic, retain) NSString *field1;
@property (nonatomic, retain) NSString *field2;
@property (nonatomic, retain) NSString *field3;
@property (nonatomic, retain) NSString *field4;
@end
Copy the codeThe code is as follows:
//
//
// Persistence2
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import ""
#define kField1Key @"Field1"
#define kField2Key @"Field2"
#define kField3Key @"Field3"
#define kField4Key @"Field4"
@implementation Fourlines
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
#pragma mark NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:field1 forKey:kField1Key];
[aCoder encodeObject:field2 forKey:kField2Key];
[aCoder encodeObject:field3 forKey:kField3Key];
[aCoder encodeObject:field4 forKey:kField4Key];
}
-(id) initWithCoder:(NSCoder *)aDecoder {
if(self = [super init]) {
field1 = [[aDecoder decodeObjectForKey:kField1Key] retain];
field2 = [[aDecoder decodeObjectForKey:kField2Key] retain];
field3 = [[aDecoder decodeObjectForKey:kField3Key] retain];
field4 = [[aDecoder decodeObjectForKey:kField4Key] retain];
}
return self;
}
#pragma mark -
#pragma mark NSCopying
- (id) copyWithZone:(NSZone *)zone {
Fourlines *copy = [[[self class] allocWithZone: zone] init];
copy.field1 = [[self.field1 copyWithZone: zone] autorelease];
copy.field2 = [[self.field2 copyWithZone: zone] autorelease];
copy.field3 = [[self.field3 copyWithZone: zone] autorelease];
copy.field4 = [[self.field4 copyWithZone: zone] autorelease];
return copy;
}
@end
Copy the codeThe code is as follows:
//
//
// Persistence2
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/>
#define kFilename @"archive"
#define kDataKey @"Data"
@interface Persistence2ViewController : UIViewController {
UITextField *filed1;
UITextField *field2;
UITextField *field3;
UITextField *field4;
}
@property (nonatomic, retain) IBOutlet UITextField *field1;
@property (nonatomic, retain) IBOutlet UITextField *field2;
@property (nonatomic, retain) IBOutlet UITextField *field3;
@property (nonatomic, retain) IBOutlet UITextField *field4;
- (NSString *)dataFilePath;
- (void)applicationWillResignActive:(NSNotification *)notification;
@end
Copy the codeThe code is as follows:
//
//
// Persistence2
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import ""
#import ""
@implementation Persistence2ViewController
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
//The complete path of the data file
- (NSString *)dataFilePath {
//Retrieve the Documents directory path. The second parameter indicates that search is restricted to our application sandbox
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//Each application has only one Documents directory
NSString *documentsDirectory = [paths objectAtIndex:0];
//Create file name
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
// When the application exits, save the data to the attribute list file.
- (void)applicationWillResignActive:(NSNotification *)notification {
Fourlines *fourlines = [[Fourlines alloc] init];
fourlines.field1 = ;
fourlines.field2 = ;
fourlines.field3 = ;
fourlines.field4 = ;
NSMutableData *data = [[NSMutableData alloc] init];// Used to store encoded data
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:fourlines forKey:kDataKey];
[archiver finishEncoding];
[data writeToFile:[self dataFilePath] atomically:YES];
[fourlines release];
[archiver release];
[data release];
}
/*
// 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]) {
//Get data for decoding from the file
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
Fourlines *fourlines = [unarchiver decodeObjectForKey:kDataKey];
[unarchiver finishDecoding];
= fourlines.field1;
= fourlines.field2;
= fourlines.field3;
= fourlines.field4;
[unarchiver release];
[data release];
}
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
3、SQLite
Copy the codeThe code is as follows:
//
//
// Persistence3
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/>
#define kFilename @"data.sqlite3"
@interface Persistence3ViewController : UIViewController {
UITextField *filed1;
UITextField *field2;
UITextField *field3;
UITextField *field4;
}
@property (nonatomic, retain) IBOutlet UITextField *field1;
@property (nonatomic, retain) IBOutlet UITextField *field2;
@property (nonatomic, retain) IBOutlet UITextField *field3;
@property (nonatomic, retain) IBOutlet UITextField *field4;
- (NSString *)dataFilePath;
- (void)applicationWillResignActive:(NSNotification *)notification;
@end
Copy the codeThe code is as follows:
//
//
// 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 of the data file
- (NSString *)dataFilePath {
//Retrieve the Documents directory path. The second parameter indicates that search is restricted to our application sandbox
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//Each application has only one Documents directory
NSString *documentsDirectory = [paths objectAtIndex:0];
//Create 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 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 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);
}
//Query
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 each line
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
4、Core Data
Copy the codeThe code is as follows:
//
//
// Persistence4
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/>
@interface PersistenceViewController : UIViewController {
UITextField *filed1;
UITextField *field2;
UITextField *field3;
UITextField *field4;
}
@property (nonatomic, retain) IBOutlet UITextField *field1;
@property (nonatomic, retain) IBOutlet UITextField *field2;
@property (nonatomic, retain) IBOutlet UITextField *field3;
@property (nonatomic, retain) IBOutlet UITextField *field4;
@end
Copy the codeThe code is as follows:
//
//
// Persistence4
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import ""
#import ""
@implementation PersistenceViewController
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
-(void) applicationWillResignActive:(NSNotification *)notification {
Persistence4AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSError *error;
for(int i = 1; i <= 4; i++) {
NSString *fieldName = [NSString stringWithFormat:@"field%d", i];
UITextField *theField = [self valueForKey:fieldName];
//Create a fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//Create entity description and associate it to the request
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line"
inManagedObjectContext:context];
[request setEntity:entityDescription];
//Set the conditions for retrieving data
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(lineNum = %d)", i];
[request setPredicate:pred];
NSManagedObject *theLine = nil;
//// Check whether a standard matching object is returned, if there is, load it, and if there is no, create a new managed object to save the text of this field.
NSArray *objects = [context executeFetchRequest:request error:&error];
if(!objects) {
NSLog(@"There was an error");
}
//if( > 0) {
// theLine = [objects objectAtIndex:0];
//} else {
//Create a new managed object to save the text of this field
theLine = [NSEntityDescription insertNewObjectForEntityForName:@"Line"
inManagedObjectContext:context];
[theLine setValue:[NSNumber numberWithInt:i] forKey:@"lineNum"];
[theLine setValue: forKey:@"lineText"];
//}
[request release];
}
//Notify context save changes
[context save:&error];
}
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
Persistence4AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
//Create an entity description
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];
//Create a request to extract the object
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
//Retrieve the object
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if(!objects) {
NSLog(@"There was an error!");
}
for(NSManagedObject *obj in objects) {
NSNumber *lineNum = [obj valueForKey:@"lineNum"];
NSString *lineText = [obj valueForKey:@"lineText"];
NSString *fieldName = [NSString stringWithFormat:@"field%d", [lineNum integerValue]];
UITextField *textField = [self valueForKey:fieldName];
= lineText;
}
[request release];
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
5、AppSettings
Copy the codeThe code is as follows:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
6. Ordinary file storage
This method means saving data to or reading it from the file by itself through IO.