码迷,mamicode.com
首页 > 其他好文 > 详细

Objective-C数据保存和读取

时间:2016-11-01 18:47:11      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:box   represent   one   变量   nsstring   blog   default   repr   library   

一、NSCoding协议中的Archiving和Unarchiving

(1)Archiving一个object,会记录这个对象的所有的properties到filesystem;

(2)Unarchiving一个object,会从data中重新创建这个object。

类中的实力要Archiving和Unarchiving,需遵守NSCoding协议,并要实现以下两个方法:

@protocol NSCoding
-(void)encodeWithCoder:(NSCoder*)aCoder;
-(instancetype)initWithCoder:(NSCoder*)aCoder;
@end

例:

//
-(void)encodeWithCoder:(NSCoder*)aCoder{
    [aCoder encodeObject:self.itemName forKey:@"itemName"];
    [aCoder encodeInt:self.valueInDollars forKey:@"valueInDollars"];
}

//
-(instancetype)initWithCoder:(NSCoder*)aCoder{
   self = [super init];
   if(self){
        _itemName = [aDecoder decodeObjectForKey:@"itemName"];
        _valueInDollars = [aDecoder decodeIntForKey:@"valueInDollars"];  
    }
   return self;  
}

类似地,

XIB file被保存,即是把views  archived  into XIB file;

当应用程序启动时,从XIB file里unarchive the views。

二、使用NSCoder的子类在sandbox中存取

应用程序的sandbox是一个目录,包括:Documents、Library(不会在应用程序退出时删除)、tmp(会在应用程序退出时删除)。

NSCoder的子类,这里指:NSKeyedArchiver和NSKeyedUnArchiver这两个类。

例:

//生成file path
-(NSString *)itemArchivePath {
  NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
  NSString *documentDirectory = [documentDirectories firstObject];
   return [ documentDirectory stringByAppendingPathComponent:@"items.archive"];
}

//
-(BOOL)saveChanges {
   NSString *path = [self itemArchivePath];
    return [NSKeyedArchiver archiveRootObject:XXX toFile:path];
}

//
-(instancetype)initPrivate {
   self = [super init];
   if(self){
       NSString *path = [self itemArchivePath];
       _privateItem = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
  }
  return self;
}
NSKeyedArchiver存对象的过程分为两步:(1)先调用encodeWithCoder来encode变量到NSKeyedArchiver;(2)再存到path。
三、用NSData写入FileSystem
例:
-(NSString*)imagePathForKey:(NSString*)key{
    NSArray *documentDirectories =....;
    NSString *documentDirectory = ...;
    return [  documentDirectory stringByAppendingPathComponent:key];
}

//写入
NSString imagePath = [self imagePathForKey:key];
NSData *data = UIImageJPEGRepresentation(image,0.5);
[data writeToFile:imagePath atomically:YES];

//删除
[[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];

//读取
UIImage *image = [UIImage imageWithContentOfFile:imagePath];
其中NSFileManager可以获取、创建、拷贝以及移动文件和目录。
 

 

Objective-C数据保存和读取

标签:box   represent   one   变量   nsstring   blog   default   repr   library   

原文地址:http://www.cnblogs.com/Xylophone/p/6020381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!