データ永続化NSKeyedArchiver
3153 ワード
NSString、NSDictionary、NSArray、NSData、NSNumberなどの基本的なデータ型は、属性リストの方法で永続化することができる.plistファイルでは、いくつかのカスタムクラスであれば、プロパティリストの方法は役に立ちません.archiverメソッドは可能です.
コードは次のとおりです.
まずpersonクラスを新規作成し、次の3つのプロパティを定義します.
それからmファイルには次のコードが書かれています.
あ、、ViewControllerと書いています.mファイルコードの場合は、ヘッダファイルにNSCodingプロトコルに従う必要があります.
実行結果は次のとおりです.
2013-09-22 13:31:39.509データ持続化archiver[1080:c 07]name=Rio,age=20,height=1.750000
注意事項:
コードは次のとおりです.
まずpersonクラスを新規作成し、次の3つのプロパティを定義します.
//
// person.h
// archiver
//
// Created by Rio.King on 13-9-22.
// Copyright (c) 2013 Rio.King. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface person : UIView<NSCoding>
@property(nonatomic, assign) int age;
@property(nonatomic, copy)NSString *name;
@property(nonatomic, assign)float height;
@end
//
// person.m
// archiver
//
// Created by Rio.King on 13-9-22.
// Copyright (c) 2013 Rio.King. All rights reserved.
//
#import "person.h"
@implementation person
#pragma mark
-(void)encodeWithCoder:(NSCoder *)encoder{
[super encodeWithCoder:encoder];//
[encoder encodeInt:self.age forKey:@"age"];
[encoder encodeObject:self.name forKey:@"name"];
[encoder encodeFloat:self.height forKey:@"height"];
}
#pragma mark
-(id)initWithCoder:(NSCoder *)decoder{
self = [super initWithCoder:decoder];//
self.age = [decoder decodeIntForKey:@"age"];
self.name = [decoder decodeObjectForKey:@"name"];
self.height = [decoder decodeFloatForKey:@"height"];
return self;
}
-(NSString *)description{
return [NSString stringWithFormat:@"name = %@, age = %d, height = %f",self.name,self.age,self.height];
}
//
-(void)dealloc{
[super dealloc];
[_name release];
}
@end
それからmファイルには次のコードが書かれています.
//
// ViewController.m
// archiver
//
// Created by Rio.King on 13-9-22.
// Copyright (c) 2013 Rio.King. All rights reserved.
//
#import "ViewController.h"
#import "person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self createPerson];
[self readPerson];
}
//
-(void)createPerson{
person *p = [[[person alloc] init] autorelease];
p.age = 20;
p.name = @"Rio";
p.height =1.75f;
// Document
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [documents stringByAppendingPathComponent:@"person.archiver"];//
[NSKeyedArchiver archiveRootObject:p toFile:path];
}
//
-(void)readPerson{
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [documents stringByAppendingPathComponent:@"person.archiver"];
person *person1 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"%@",person1);
}
@end
あ、、ViewControllerと書いています.mファイルコードの場合は、ヘッダファイルにNSCodingプロトコルに従う必要があります.
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<NSCoding>
@end
実行結果は次のとおりです.
2013-09-22 13:31:39.509データ持続化archiver[1080:c 07]name=Rio,age=20,height=1.750000
注意事項: