zoukankan      html  css  js  c++  java
  • (IOS)数据持久化

    1.属性列表序列化

    2.模型对象归档

    3.嵌入式SQLite3

    4.Core Data

    5.应用程序设置

    6.UIDocument管理文档存储

    7.iCloud

    Demo界面:

    1.属性列表序列化

    即从porperty list中直接读写plist对象(NSString, NSData, NSArray, or NSDictionary objects),其中容器对象中的实例亦要为plist对象。

    根视图控制器:

     1 #define kFilename @"data.plist"
     2  
     3 - (void)viewDidLoad
     4 {
     5     [super viewDidLoad];
     6     NSString *path=[self dataFilePath]; //获取document下的指定文件路径
     7     NSLog(@"%@",path);
     8     if([[NSFileManager defaultManager] fileExistsAtPath:path])
     9     {
    10         NSArray *array=[[NSArray alloc] initWithContentsOfFile:path];
    11         self.field1.text=[array objectAtIndex:0];
    12         self.field2.text=[array objectAtIndex:1];
    13         self.field3.text=[array objectAtIndex:2];
    14         self.field4.text=[array objectAtIndex:3];
    15     }
    16     
    17     UIApplication *app =[UIApplication sharedApplication];
    18     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
    19 }
    20  
    21 -(NSString *)dataFilePath
    22 {
    23     NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    24     NSString *documentsDirectory=[paths objectAtIndex:0];
    25     return [documentsDirectory stringByAppendingPathComponent:kFilename];
    26 }
    27  
    28 -(void)applicationWillResignActive:(NSNotification *)notification;
    29 {
    30     NSMutableArray *array=[[NSMutableArray alloc] init];
    31     [array addObject:field1.text];
    32     [array addObject:field2.text];
    33     [array addObject:field3.text];
    34     [array addObject:field4.text];
    35     [array writeToFile:[self dataFilePath] atomically:YES]; //没有则自动创建文件,和c中的fopen("","w")一样,先清空内容再写入。
    36     //所以没有判断是否文件存在。
    37 }
    沙盒中的Documents文件夹有生成data.plist,且用xml协议保存了数据。
     
     

    2.模型对象归档

    NSString、NSArray、NSData、NSDictionary都实现了NSCoding协议,可直接通过调用writeToFile归档。

    但如果想保持对象类型的数据,则需要到该方法灵活实现。首先可将需归档的对象先实现NSCoding协议,重写encodeWithCode方法和initWithCode方法,然后通过NSKeyedArchiver转换为NSData,然后通过NSData的writeToFile方法写入到文件,或者将转换后的NSData放入到NSArray或NSDictionary中调用writeToFile写入到文件便可实现包装了自定义类型的数据和字典的归档;

    通过NSKeyedUnarchiver读取归档文件到对象,或者通过NSArray的arrrayWithContentsOfFile或NSDictionary的dictionaryWithContentsOfFile到数组对象或字典,然后取出序列化过的自定义对象(即自定义对象的NSData形式),然后通过NSKeyedUnarchiver反归档到对象。

    根视图控制器:
    #define kFilename @"archive" 
    #define kDataKey @"Data" 
    -(NSString *)dataFilePath 
     {
        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *documentsDirectory=[paths objectAtIndex:0];         return [documentsDirectory stringByAppendingPathComponent:kFilename]; 
     } 
    
    - (void)viewDidLoad 
     { 
        [super viewDidLoad]; 
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) 
    {
        NSMutableData *data=[[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]]; 
        NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data]; 
        BIDFourLines *fourlines=[unarchiver         decodeObjectForKey:kDataKey]; 
        [unarchiver finishDecoding]; 
        field1.text=fourlines.field1; 
        field2.text=fourlines.field2; 
        field3.text=fourlines.field3; 
        field4.text=fourlines.field4;
    } 
    
        UIApplication *app =[UIApplication sharedApplication];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app]; 
    } 
    
    -(void)applicationWillResignActive:(NSNotification *)notification;
    { 
        BIDFourLines *fourlines=[[BIDFourLines 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在收到编码后数据自动转为二进制写到data 
        [archiver encodeObject:fourlines forKey:kDataKey];//以Data为键编码 
        [archiver finishEncoding]; 
        [data writeToFile:[self dataFilePath] atomically:YES]; //将data写入Documents中的archiver中。
    
    }

    /*

    writeToFile:

    这方法其实是写到plist文件(生成plist文件中的一个档)中的,根据官方文档描述If the array’s contents are all property list objects (NSString, NSData, NSArray, or NSDictionary objects), the file written by this method can be used to initialize a new array with the class method arrayWithContentsOfFile: or the instance method initWithContentsOfFile:. This method recursively validates that all the contained objects are property list objects before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

    */

    模型对象:
     1 #pragma mark NSCoding
     2 -(void)encodeWithCoder:(NSCoder *)aCoder
     3 {
     4     [aCoder encodeObject:field1 forKey:kField1Key];
     5     [aCoder encodeObject:field2 forKey:kField2Key];
     6     [aCoder encodeObject:field3 forKey:kField3Key];
     7     [aCoder encodeObject:field4 forKey:kField4Key];
     8 }
     9  
    10 -(id)initWithCoder:(NSCoder *)aDecoder
    11 {
    12     if(self=[super init])
    13     {
    14         self.field1=[aDecoder decodeObjectForKey:kField1Key];
    15         self.field2=[aDecoder decodeObjectForKey:kField2Key];
    16         self.field3=[aDecoder decodeObjectForKey:kField3Key];
    17         self.field4=[aDecoder decodeObjectForKey:kField4Key];
    18     }
    19     return self;
    20 }
    21  
    22 #pragma mark NSCopying
    23 -(id)copyWithZone:(NSZone *)zone
    24 {
    25     BIDFourLines *copy=[[[self class] allocWithZone:zone] init];
    26     copy.field1=[self.field1 copyWithZone:zone];
    27     copy.field2=[self.field2 copyWithZone:zone];
    28     copy.field3=[self.field3 copyWithZone:zone];
    29     copy.field4=[self.field4 copyWithZone:zone];
    30     
    31     return copy;
    32 }

    沙盒中的Documents文件夹生成archiver文件(无扩展名,加上.plist扩展名即可查看编码后保存的数据内容)。

     
     

    3.嵌入式SQLite3

    需要先导入sqlite3 的 api 或 framework。
     
     1 #define kFilename @"data.sqlite3"
     2  
     3 - (void)viewDidLoad
     4 {
     5     [super viewDidLoad];
     6 sqlite3 *database;
     7     if(sqlite3_open([[self dataFilePath] UTF8String], &database)!=SQLITE_OK)
     8      {
     9          sqlite3_close(database);
    10          NSAssert(0, @"Failed to open database");
    11      }
    12     
    13     NSString *createSQL=@"CREATE TABLE IF NOT EXISTS FIELDS"
    14                             "(ROW INTEGER PRIMARY KEY , FIELD_DATA TEXT);";
    15     char *errorMsg;
    16     if(sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg)!=SQLITE_OK)
    17        {
    18            sqlite3_close(database);
    19            NSAssert(0, @"Error creating table: %s",errorMsg);
    20        }
    21     NSString *query=@"SELECT ROW, FIELD_DATA FROM FIELDS ORDER BY ROW";
    22     sqlite3_stmt *statement;
    23     if(sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil)==SQLITE_OK)
    24     {
    25         while (sqlite3_step(statement)==SQLITE_ROW)  //移动位置指针
    26        {
    27             int row=sqlite3_column_int(statement,0);
    28             char *rowData=(char *)sqlite3_column_text(statement, 1);
    29             
    30             NSString *fieldName=[[NSString alloc] initWithFormat:@"field%d",row];
    31             NSString *fieldValue=[[NSString alloc] initWithUTF8String:rowData];
    32             UITextField *field=[self valueForKey:fieldName];
    33             field.text=fieldValue;
    34         }
    35         sqlite3_finalize(statement);
    36     }
    37     sqlite3_close(database);
    38                         
    39     
    40     UIApplication *app =[UIApplication sharedApplication];
    41     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
    42 }
    43  
    44 -(void)applicationWillResignActive:(NSNotification *)notification;
    45 {
    46     sqlite3 *database;
    47     if(sqlite3_open([[self dataFilePath] UTF8String], &database)!=SQLITE_OK)
    48     {
    49         sqlite3_close(database);
    50         NSAssert(0, @"Failed to open database");
    51     }
    52     
    53     for (int i=1; i<=4; i++) {
    54         NSString *fieldName=[[NSString alloc] initWithFormat:@"field%d",i];
    55         UITextField *field=[self valueForKey:fieldName];
    56         
    57         char *updata="INSERT OR REPLACE INTO FIELDS (ROW, FIELD_DATA) VALUES(? , ?);";
    58         sqlite3_stmt *stmt;
    59         if (sqlite3_prepare_v2(database, updata, -1, &stmt, nil)==SQLITE_OK) {
    60             sqlite3_bind_int(stmt, 1, i);
    61             sqlite3_bind_text(stmt, 2, [field.text UTF8String],-1,NULL);
    62         }
    63         if(sqlite3_step(stmt)!=SQLITE_DONE)
    64         {
    65             NSAssert(0,@"Error updating table.");
    66         }
    67         sqlite3_finalize(stmt);
    68     }
    69     sqlite3_close(database);
    70 }
    沙盒中的Documents文件夹生成data.sqlite3文件(未知直读方法)。
     
     

    4.Core Data

    创建项目时选空模板才有use core data (ORM对象关系映射)选项 选择。之后再配置xcdatamodel和根视图。
    xcdatamodel配置:

    根视图控制器:
     1 - (void)viewDidLoad
     2 {
     3     [super viewDidLoad];
     4     // Do any additional setup after loading the view from its nib.
     5     
     6     BIDAppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];
     7     NSManagedObjectContext *context=[appDelegate managedObjectContext];
     8     NSEntityDescription *entityDecription=[NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];//关联实体与上下文
     9     NSFetchRequest *request=[[NSFetchRequest alloc] init];
    10     [request setEntity:entityDecription];//设置抓取实体
    11     NSError *error;
    12     /*因为要抓取实体中的所有项,所以没有设置抓取属性*/
    13     NSArray *objects=[context executeFetchRequest:request error:&error];//从实体中抓取到上下文,且上下文进行跟踪对象
    14     if(objects==nil)
    15         NSLog(@"There was an error!");
    16     for (NSManagedObject *object in objects)
    17     {
    18         NSNumber *lineNum=[object valueForKey:@"lineNum"]; //读取抓取出的第n个对象的lineNum属性
    19         NSString *lineText=[object valueForKey:@"lineText"];
    20         
    21         NSString *fieldname=[[NSString alloc] initWithFormat: @"line%d",[lineNum integerValue]];
    22         UITextField *field=[self valueForKey:fieldname];
    23         field.text=lineText;
    24     }
    25     
    26     UIApplication *app=[UIApplication sharedApplication];
    27     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
    28 }
    29  
    30 -(void)applicationWillResignActive:(NSNotification *)notification
    31 {
    32     BIDAppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];
    33     NSManagedObjectContext *context=[appDelegate managedObjectContext];
    34     NSError *error;
    35     
    36     for (int i=1; i<=4; i++) {
    37         NSString *fieldname=[[NSString alloc] initWithFormat:@"line%d",i];
    38         UITextField *field=[self valueForKey:fieldname];
    39         
    40         NSFetchRequest *request=[[NSFetchRequest alloc] init];
    41         
    42         NSEntityDescription *entityDescritption=[NSEntityDescription entityForName:@"Line" inManagedObjectContext:context];
    43         [request setEntity:entityDescritption];
    44         
    45         NSPredicate *predicate=[NSPredicate predicateWithFormat:@"(lineNum=%d)",i];
    46         [request setPredicate:predicate];
    47         
    48         NSArray *objects=[context executeFetchRequest:request error:&error];//抓取上下文中的托管对象集
    49         NSManagedObject *theLine=nil;
    50         
    51         if(objects==nil)
    52             NSLog(@"There was an error!");
    53         if([objects count]>0)
    54         {
    55             /*因设置了抓取属性,每次按抓取属性在实体抓取的上下文中的托管对象集里都只有一个对应的托管对象(在此例对应抓取属性的只有一个)*/
    56             theLine=[objects objectAtIndex:0];//取托管对象
    57         }
    58         else
    59         {
    60             /*在实体中插入新的托管对象,且返回该对象和放入上下文中跟踪*/
    61             theLine=[NSEntityDescription insertNewObjectForEntityForName:@"Line" inManagedObjectContext:context];
    62         }
    63         [theLine setValue:[NSNumber numberWithInt:i] forKey:@"lineNum"];
    64         [theLine setValue:field.text forKey:@"lineText"];
    65     }
    66     [context save:&error];//跟踪结束,保存进实体
    67 }
     应用程序委托:
     1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
     2 {
     3     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
     4     // Override point for customization after application launch.
     5     self.rootcontroller=[[BIDViewController alloc] initWithNibName:@"BIDViewController" bundle:nil];
     6     UIView *rootView=self.rootcontroller.view;
     7     CGRect viewFrame=rootView.frame;
     8     viewFrame.origin.y+=[UIApplication sharedApplication].statusBarFrame.size.height;
     9     rootView.frame=viewFrame;
    10     [self.window addSubview:rootView];
    11     self.window.backgroundColor = [UIColor whiteColor];
    12     [self.window makeKeyAndVisible];
    13     return YES;
    14 }
    沙盒中的Documents文件夹生成Core_Data_Persistence.sqlite文件(未知直读方法)。
     
     

    其它例子

    5.应用程序设置(UserDefault)

    程序使用该方法保持的数据,可在iphone的settings中查看和设置。

    添加setting.bundle,在root.plist中配置好要保存的数据项和settings中显示的分组界面。

    应用程序委托:
    1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    2 {
    3     // Override point for customization after application launch.
    4     NSDictionary *defaults=[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],kWarpDriveKey,[NSNumber numberWithInt:5],kWarpFactorKey,@"Greed",kFavoriteSinKey, nil];
    5     [[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
    6     return YES;
    7 }//第一次运行程序时,对设置束赋默认初值。
     视图控制器:
    1     NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    2     usernameLabel.text=[defaults objectForKey:kUsernameKey];
    3     //读取方法,利用NSUserDefaults的单例方法。键值为设置束中的每项的Identifier。
    4  
    5     NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    6     [defaults setBool:engineSwitch.on forKey:kWarpDriveKey];
    7     //保存方法
    在Settings中可设置应用程序,在应用程序中亦可设置反馈给Settings。Documents文件夹中没有生成数据保存文件。
     
     

    6.UIDocument管理文档存储

    模型类:
    先建立作为UIDocument子类的数据模型类,在类里实现以下UIDocument方法和其它模型方法
     1 -(id)contentsForType:(NSString *)typeName error:(NSError *__autoreleasing *)outError
     2 {
     3     NSLog(@"saving document to URL %@",self.fileURL);//输出保存的路径
     4     return [bitmap copy];//bitmap为保存的mutabledata数据
     5 }//保存
     6  
     7 -(BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError *__autoreleasing *)outError
     8 {
     9     NSLog(@"loading document from URL %@",self.fileURL);
    10     self.bitmap =[contents copy];
    11     return true;
    12 }//加载
     控制器:
    读取文档路径集
    1 NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    2 NSString *path=[paths objectAtIndex:0];
    3 NSFileManager *fm=[NSFileManager defaultManager];
    4 NSError *dirError;
    5 NSArray *files=[fm contentsOfDirectoryAtPath:path error:&dirError];
    6 //数组内排序
    7 self.documentFileNames=files;
     读取文档URL路径
    1 -(NSURL *)urlForFilename:(NSString *)filename
    2 {
    3     NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    4     NSString *documentDirectory=[paths objectAtIndex:0];
    5     NSString *filePath=[documentDirectory stringByAppendingPathComponent:filename];
    6     NSURL *url=[NSURL fileURLWithPath:filePath];
    7     return url;
    8
     创建文档,并设置保存
     1         NSString *filename=[NSString stringWithFormat:@"%@.tinypix",[alertView textFieldAtIndex:0].text];
     2         NSURL *saveUrl=[self urlForFilename:filename];
     3         self.chooseDocument=[[BIDTinyPixDocument alloc] initWithFileURL:saveUrl];//创建UIDocument子类实例对象
     4         [chooseDocument saveToURL:saveUrl forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
     5             if(success)
     6             {
     7                 NSLog(@"save OK");
     8                 //addition
     9             }
    10             else
    11                 NSLog(@"failed to save!");
    12          }];
     打开文档
     1         self.chooseDocument=[[BIDTinyPixDocument alloc] initWithFileURL:docUrl];
     2         [self.chooseDocument openWithCompletionHandler:^(BOOL success) {
     3             if(success)
     4             {
     5                 NSLog(@"load OK");
     6                 //addition
     7             }
     8             else
     9                 NSLog(@"failed to load!");
    10         }];
     关闭文档(保持编辑数据)
    1 UIDocument *doc=self.chooseDocument;
    2 [doc closeWithCompletionHandler:nil];
    沙盒中的Documents文件夹生成filename.tinypix文件。
     
     

    7.iCloud

    首先设置好provisioning profile和Entitlements部分,获取icloud的权限。
    控制器:
    查询icloud中指定扩展名的文档路径集,得到路径后保存方法和文档保存方法一致。
     1 -(void)reloadFiles
     2 {
     3     NSFileManager *fileManager=[NSFileManager defaultManager];
     4     NSURL *cloudURL=[fileManager URLForUbiquityContainerIdentifier:nil];
     5     NSLog(@"got cloudURL %@",cloudURL);
     6     
     7     self.query=[[NSMetadataQuery alloc] init];
     8  
     9     query.predicate=[NSPredicate predicateWithFormat:@"%K like '*.tinypix'",NSMetadataItemFSNameKey];
    10     query.searchScopes=[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope];
    11  
    12     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUbiquitousDocuments:) name:NSMetadataQueryDidFinishGatheringNotification object:nil];
    13     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUbiquitousDocuments:) name:NSMetadataQueryDidUpdateNotification object:nil];
    14  
    15     [query startQuery];
    16 17  
    18 -(void)updateUbiquitousDocuments:(NSNotification *)notification
    19 {
    20     self.documentURLs=[NSMutableArray array];
    21     self.documentFileNames=[NSMutableArray array];
    22     NSLog(@"updateUbiquitousDocuments, results= %@",self.query.results);
    23  
    24     NSArray *results=[self.query.results sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    25         NSMetadataItem *item1=obj1;
    26         NSMetadataItem *item2=obj2;
    27         return [[item2 valueForAttribute:NSMetadataItemFSCreationDateKey] compare:[item1 valueForAttribute:NSMetadataItemFSCreationDateKey]];
    28     }];
    29  
    30     for(NSMetadataItem *item in results)
    31     {
    32         NSURL *url=[item valueForAttribute:NSMetadataItemURLKey];
    33         [self.documentURLs addObject:url];
    34         [(NSMutableArray *)documentFileNames addObject:[url lastPathComponent]];
    35     }
    36     [self.tableView reloadData];
    37 }
    38  
    39 -(NSURL *)urlForFilename:(NSString *)filename
    40 {
    41     NSURL *baseURL=[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
    42     NSURL *pathURL=[baseURL URLByAppendingPathComponent:@"Documents"];
    43     NSURL *destinationURL=[pathURL URLByAppendingPathComponent:filename];
    44     return destinationURL;
    45 }
     icloud上读写首选项
    1     NSUbiquitousKeyValueStore *prefs=[NSUbiquitousKeyValueStore defaultStore];
    2     [prefs setLongLong:selectedColorIndex forKey:@"selectedColorIndex"];
    3     self.selectedColorIndex=[prefs longLongForKey:@"selectedColorIndex"];
  • 相关阅读:
    Android中设置APP应用字体不缩放,文字不随系统字体大小变化
    day02 作业
    day01
    2018.11.2
    2018.11.1
    2018.10.25
    2018.10.24
    2018.10.23
    2018.10.20
    2018.10.19学习总结
  • 原文地址:https://www.cnblogs.com/mingfung-liu/p/3173058.html
Copyright © 2011-2022 走看看