以代码实例总结iOS应用开发中数据的存储方式

ios数据存储包括以下几种存储机制:

  • 属性列表
  • 对象归档
  • SQLite3
  • CoreData
  • AppSettings
  • 普通文件存储

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:@"lineText"]; 
        //} 
        [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 *lineText = [obj valueForKey:@"lineText"]; 
        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保存到文件,或从文件读取。

(0)

相关推荐

  • 详解iOS开发中app的归档以及偏好设置的存储方式

    ios应用数据存储方式(归档) 一.简单说明 在使用plist进行数据存储和读取,只适用于系统自带的一些常用类型才能用,且必须先获取路径相对麻烦: 偏好设置(将所有的东西都保存在同一个文件夹下面,且主要用于存储应用的设置信息) 归档:因为前两者都有一个致命的缺陷,只能存储常用的类型.归档可以实现把自定义的对象存放在文件中. 二.代码示例 1.文件结构 2.代码示例 YYViewController.m文件 复制代码 代码如下: // //  YYViewController.m //  02-归

  • 详解iOS的数据存储

    iOS应用数据存储的常用方式 1.XML属性列表(plist)归档. 2.Preference(偏好设置). 3.NSKeyedArchiver归档. 4.SQLite3 5.Core Data 应用沙盒 每个iOS应用都有自己的应用沙盒(应用沙盒就是文件系统目录)与其他文件系统隔离.应用必须待在自己的沙盒里,其他应用不能访问该沙盒. 模拟器应用沙盒的根路径在: (apple是用户名, 6.0是模拟器版本) /Users/apple/Library/Application Support/iPh

  • IOS开发之路--C语言存储方式和作用域

    概述 基本上每种语言都要讨论这个话题,C语言也不例外,因为只有你完全了解每个变量或函数存储方式.作用范围和销毁时间才可能正确的使用这门语言.今天将着重介绍C语言中变量作用范围.存储方式.生命周期.作用域和可访问性. 变量作用范围 存储方式 可访问性 变量作用范围 在C语言中变量从作用范围包括全局变量和局部变量.全局变量在定义之后所有的函数中均可以使用,只要前面的代码修改了,那么后面的代码中再使用就是修改后的值:局部变量的作用范围一般在一个函数内部(通常在一对大括号{}内),外面的程序无法访问它,

  • 详解iOS App开发中session和coockie的用户数据存储处理

    NSURLSession 在iOS7之后,NSURLSession作为系统推荐使用的HTTP请求框架,在进行前台请求的情况下,NSURLSession与NSURLConnection并无太大差异,对于后台的请求,NSURLSession更加灵活的优势就将展现无遗. 1.NSURLSession集合的类型 NSURLSession类提供3中Session类型: (1)Default类型:提供前台请求相关方法,支持配置缓存,身份凭证等. (2)Ephemeral类型:即时的请求类型,不使用缓存,身份

  • 详解iOS应用开发中Core Data数据存储的使用

    1.如果想创建一个带有coreData的程序,要在项目初始化的时候勾选中   2.创建完成之后,会发现在AppDelegate里多出了几个属性,和2个方法 复制代码 代码如下: <span style="font-size:18px;">    @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;  @property (readonly, strong,

  • 深入讲解iOS开发中应用数据的存储方式

    XML属性列表-plist 一.应用沙盒 每个iOS应用都有⾃己的应⽤沙盒(应用沙盒就是文件系统目录),与其他文件系统隔离.应⽤必须待在⾃己的沙盒里,其他应用不能访问该沙盒(提示:在IOS8中已经开放访问) 应⽤沙盒的文件系统⽬录,如下图所示(假设应用的名称叫Layer) 模拟器应⽤用沙盒的根路径在: (apple是⽤用户名, 7.0是模拟器版本) /Users/apple/Library/Application Support/iPhone Simulator/7.0/Applications

  • IOS开发使用KeychainItemWrapper 持久存储用户名和密码

    首先从官网下载 KeychainItemWrapper.h KeychainItemWrapper.m 将这两个文件导入项目中 不过该文件是手动释放的 所以要使用这个文件需要先做一些处理: 如果要使用KeychainItemWrapper.h类 在CompileSources中选中该类 添加-fno-objc-arc 接下来直接上代码: KeychainItemWrapper *keychain=[[KeychainItemWrapper alloc] initWithIdentifier:@"

  • 以代码实例总结iOS应用开发中数据的存储方式

    ios数据存储包括以下几种存储机制: 属性列表 对象归档 SQLite3 CoreData AppSettings 普通文件存储 1.属性列表 复制代码 代码如下: //  //  Persistence1ViewController.h  //  Persistence1  //  //  Created by liu lavy on 11-10-3.  //  Copyright 2011 __MyCompanyName__. All rights reserved.  //    #imp

  • Android开发笔记之Android中数据的存储方式(一)

    对于开发平台来讲,如果对数据的存储有良好的支持,那么对应用程序的开发将会有很大的促进作用. 总体的来讲,数据存储方式有三种:一个是文件,一个是数据库,另一个则是网络.其中文件和数据库可能用的稍多一些,文件用起来较为方便,程序可以自己定义格式:数据库用起稍烦锁一些,但它有它的优点,比如在海量数据时性能优越,有查询功能,可以加密,可以加锁,可以跨应用,跨平台等等:网络,则用于比较重要的事情,比如科研,勘探,航空等实时采集到的数据需要马上通过网络传输到数据处理中心进行存储并进行处理,有实时性的需求等.

  • Android开发笔记之Android中数据的存储方式(二)

    我们在实际开发中,有的时候需要储存或者备份比较复杂的数据.这些数据的特点是,内容多.结构大,比如短信备份等.我们知道SharedPreferences和Files(文本文件)储存这种数据会非常的没有效率.如果学过JavaWeb的朋友,首先可能想到的是数据库.当然了数据库是一个方案,那么是否还有其他的解决方案呢?今天我们在讲下Android开发笔记之Android中数据的存储方式(一)提到的除了SharedPreferences和Files(文本文件)以外的其他几种数据储存方式:xml文件.SQL

  • Android应用开发中数据的保存方式总结

    一.保存文件到手机内存 /** * 保存数据到手机rom的文件里面. * @param context 应用程序的上下文 提供环境 * @param name 用户名 * @param password 密码 * @throws Exception */ public static void saveToRom(Context context, String name , String password) throws Exception{ //File file = new File("/da

  • Android开发之数据的存储方式详解

    在Android中,数据的存储分为两种方式: 1.直接以文件的形式存储在目录中 2.以json格式存储在数据库中 将数据以文件的存储又分为两种方式: 1.生成.txt文件 2.生成xml文件 那么今天就来详细的说一下以文件的形式存储,由于没有讲到数据库,在之后的课程中会讲到json格式存储在数据库中. 一.生成.txt文件 文件的生成无非就是我们Java中学习的输入输出流中的一部分,有Java基础相信都是很容易理解的,因为它真的很简单啦~~ 1.生成目录可以分为两种: 1)本机 2)SD卡 2.

  • 实例讲解iOS应用开发中UIPickerView滚动选择栏的用法

    基础 1.UIPickerView 属性 数据源(用来告诉UIPickerView有多少列多少行) 复制代码 代码如下: @property(nonatomic,assign) id dataSource; 代理(用来告诉UIPickerView每1列的每1行显示什么内容,监听UIPickerView的选择) 复制代码 代码如下: @property(nonatomic,assign) id   delegate; 是否要显示选中的指示器 复制代码 代码如下: @property(nonatom

  • 实例讲解iOS应用开发中使用UITableView创建自定义表格

    一.带索引目录的表视图 1.效果图 2.数据源 本想获取通讯录中得名字,但为了用模拟器调试方便,就写死了数据,所以也只写了部分字母,总之有那么点意思就成 复制代码 代码如下: @interface ViewController ()<UITableViewDataSource,UITableViewDelegate> {     NSArray *sectionTitles; // 每个分区的标题     NSArray *contentsArray; // 每行的内容 } /** @brie

  • iOS应用开发中SQLite的初步配置指南

    iOS开发数据库篇-SQLite简单介绍 一.离线缓存 在项目开发中,通常都需要对数据进行离线缓存的处理,如新闻数据的离线缓存等. 说明:离线缓存一般都是把数据保存到项目的沙盒中.有以下几种方式 (1)归档:NSCodeing.NSKeyedArchiver (2)偏好设置:NSUserDefaults (3)Plist存储:writeToFile 提示:上述三种方法都有一个致命的缺点,那就是都无法存储大批量的数据,有性能的问题. 举例:使用归档 两个问题: (1)数据的存取都必须是完整的,要求

  • asp.net开发中常见公共捕获异常方式总结(附源码)

    本文实例总结了asp.net开发中常见公共捕获异常方式.分享给大家供大家参考,具体如下: 前言:在实际开发过程中,对于一个应用系统来说,应该有自己的一套成熟的异常处理框架,这样当异常发生时,也能得到统一的处理风格,将异常信息优雅地反馈给开发人员和用户.我们都知道,.net的异常处理是按照"异常链"的方式从底层向高层逐层抛出,如果不能尽可能地早判断异常发生的边界并捕获异常,CLR会自动帮我们处理,但是这样系统的开销是非常大的,所以异常处理的一个重要原则是"早发现早抛出早处理&q

  • JavaScript中localStorage对象存储方式实例分析

    本文实例讲述了JavaScript中localStorage对象存储方式.分享给大家供大家参考,具体如下: [Local storage limitations]文章中提及JavaScript里的local storge的限制,例子中在localStorage里存储了一个bool型的数据,但是却没有像我们期待的一样进行存储. 当我们存储布尔型,数值型,字符串型时,localStorage对象会将我们存储的数据默认转为字符串字面量. localStorage[0] = false;// "fals

随机推荐