读书人

objective C中数据持久化模式1-对象归

发布时间: 2013-10-10 14:14:51 作者: rapoo

objective C中数据持久化方式1--对象归档

第一、数据持久化的方式:

NSKeyedArchiver--对象归档

属性列表化(NSArray、NSDictionary、NSUserDefault)

SQlite数据库、CoreData数据库

其中第一、二种方式针对数据量小的数据,第三种方式针对大数据,归档的文件是加密的,属性列表明文的。

归档的形式;

对foundation库中对象进行归档

自定义对象的归档(需要实现归档协议:NSCoding)

第二 最简单归档和解归档的实现代码:

        NSString *homeDictory=NSHomeDirectory();        NSString *homePath=[homeDictory stringByAppendingPathComponent:@"Desktop/usertest.archive"];                NSMutableData *data=[NSMutableData data];        NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc] initForWritingWithMutableData:data];                NSArray *nameArray=[NSArray arrayWithObjects:@"andy",@"yang", nil];        [archiver encodeInt:100 forKey:@"age"];        [archiver encodeObject:nameArray forKey:@"names"];        [archiver finishEncoding];        [archiver release];                if ([data writeToFile:homePath atomically:YES])        {            NSData *data2=[NSData dataWithContentsOfFile:homePath];            NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data2];            int age=[unarchiver decodeIntForKey:@"age"];            NSArray *array2=[unarchiver decodeObjectForKey:@"names"];            NSLog(@"%d",age);            NSLog(@"%@",array2);            [unarchiver release];        } else        {                        NSLog(@"write to file wrong");        }                        NSLog(@"Hello, World!");            }


读书人网 >移动开发

热点推荐