IOS數據存儲包含以下幾種存儲機制:
1、屬性列表
//
// Persistence1ViewController.h
// Persistence1
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#define kFilename @"data.plist"
@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
//
// Persistence1ViewController.m
// Persistence1
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "Persistence1ViewController.h"
@implementation Persistence1ViewController
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
//數據文件的完全途徑
- (NSString *)dataFilePath {
//檢索Documents目次途徑。第二個參數表現將搜刮限制在我們的運用法式沙盒中
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//每一個運用法式只要一個Documents目次
NSString *documentsDirectory = [paths objectAtIndex:0];
//創立文件名
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
//運用法式加入時,將數據保留到屬性列表文件
- (void)applicationWillResignActive:(NSNotification *)notification {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject: field1.text];
[array addObject: field2.text];
[array addObject: field3.text];
[array addObject: field4.text];
[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];
//檢討數據文件能否存在
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
field1.text = [array objectAtIndex:0];
field2.text = [array objectAtIndex:1];
field3.text = [array objectAtIndex:2];
field4.text = [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、對象歸檔
//
// Fourlines.h
// Persistence2
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
@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
//
// Fourlines.m
// Persistence2
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "Fourlines.h"
#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
//
// Persistence2ViewController.h
// Persistence2
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#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
//
// Persistence2ViewController.m
// Persistence2
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "Persistence2ViewController.h"
#import "Fourlines.h"
@implementation Persistence2ViewController
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
//數據文件的完全途徑
- (NSString *)dataFilePath {
//檢索Documents目次途徑。第二個參數表現將搜刮限制在我們的運用法式沙盒中
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//每一個運用法式只要一個Documents目次
NSString *documentsDirectory = [paths objectAtIndex:0];
//創立文件名
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
//運用法式加入時,將數據保留到屬性列表文件
- (void)applicationWillResignActive:(NSNotification *)notification {
Fourlines *fourlines = [[Fourlines alloc] init];
fourlines.field1 = field1.text;
fourlines.field2 = field2.text;
fourlines.field3 = field3.text;
fourlines.field4 = field4.text;
NSMutableData *data = [[NSMutableData alloc] init];//用於存儲編碼的數據
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];
//檢討數據文件能否存在
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
//從文件獲得用於解碼的數據
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
Fourlines *fourlines = [unarchiver decodeObjectForKey:kDataKey];
[unarchiver finishDecoding];
field1.text = fourlines.field1;
field2.text = fourlines.field2;
field3.text = fourlines.field3;
field4.text = 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
//
// Persistence3ViewController.h
// Persistence3
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#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
//
// Persistence3ViewController.m
// Persistence3
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "Persistence3ViewController.h"
#import <sqlite3.h>
@implementation Persistence3ViewController
@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;
//數據文件的完全途徑
- (NSString *)dataFilePath {
//檢索Documents目次途徑。第二個參數表現將搜刮限制在我們的運用法式沙盒中
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//每一個運用法式只要一個Documents目次
NSString *documentsDirectory = [paths objectAtIndex:0];
//創立文件名
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
//運用法式加入時,將數據保留到屬性列表文件
- (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;
//將SQL語句編譯為sqlite外部一個構造體(sqlite3_stmt),相似java JDBC的PreparedStatement預編譯
if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == SQLITE_OK) {
//在bind參數的時刻,參數列表的index從1開端,而掏出數據的時刻,列的index是從0開端
sqlite3_bind_int(stmt, 1, i);
sqlite3_bind_text(stmt, 2, [field.text UTF8String], -1, NULL);
} else {
NSAssert(0, @"Error:Failed to prepare statemen");
}
//履行SQL文,獲得成果
int result = sqlite3_step(stmt);
if(result != SQLITE_DONE) {
NSAssert1(0, @"Error updating table: %d", result);
}
//釋放stmt占用的內存(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];
//檢討數據文件能否存在
if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
//翻開數據庫
sqlite3 *database;
if(sqlite3_open([filePath UTF8String], &database) != SQLITE_OK) {
sqlite3_close(database);
NSAssert(0, @"Failed to open database");
}
//創立表
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);
}
//查詢
NSString *query = @"SELECT ROW, FIELD_DATA FROM FIELDS ORDER BY ROW";
sqlite3_stmt *statement;
//設置nByte可以加快操作
if(sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_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];
field.text = fieldValue;
[fieldName release];
[fieldValue release];
}
//釋放statement占用的內存(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
//
// PersistenceViewController.h
// Persistence4
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@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
//
// PersistenceViewController.m
// Persistence4
//
// Created by liu lavy on 11-10-3.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "PersistenceViewController.h"
#import "Persistence4AppDelegate.h"
@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];
//創立提取要求
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//創立實體描寫並聯系關系到要求
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line"
inManagedObjectContext:context];
[request setEntity:entityDescription];
//設置檢索數據的前提
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(lineNum = %d)", i];
[request setPredicate:pred];
NSManagedObject *theLine = nil;
////檢討能否前往了尺度婚配的對象,假如有則加載它,假如沒有則創立一個新的托管對象來保留此字段的文本
NSArray *objects = [context executeFetchRequest:request error:&error];
if(!objects) {
NSLog(@"There was an error");
}
//if(objects.count > 0) {
// theLine = [objects objectAtIndex:0];
//} else {
//創立一個新的托管對象來保留此字段的文本
theLine = [NSEntityDescription insertNewObjectForEntityForName:@"Line"
inManagedObjectContext:context];
[theLine setValue:[NSNumber numberWithInt:i] forKey:@"lineNum"];
[theLine setValue:theField.text forKey:@"l.netext"];
//}
[request release];
}
//告訴高低文保留更改
[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];
//創立一個實體描寫
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];
//創立一個要求,用於提取對象
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
//檢索對象
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 *l.netext = [obj valueForKey:@"l.netext"];
NSString *fieldName = [NSString stringWithFormat:@"field%d", [lineNum integerValue]];
UITextField *textField = [self valueForKey:fieldName];
textField.text = 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
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
6、通俗文件存儲
這類方法即本身將數據經由過程IO保留到文件,或從文件讀取。
【以代碼實例總結iOS運用開辟中數據的存儲方法】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!