我有一個NSMutableArray,它包含Person類型的對象(NSString,NSString,int) 我正在尋找一種簡單的方法將此數組保存到磁盤並稍後重新加載。將NSMutableArray保存到磁盤
我讀了很多關於序列化,但我從來沒有這樣做過。也許這對我來說並不是最簡單的方式。
我有一個NSMutableArray,它包含Person類型的對象(NSString,NSString,int) 我正在尋找一種簡單的方法將此數組保存到磁盤並稍後重新加載。將NSMutableArray保存到磁盤
我讀了很多關於序列化,但我從來沒有這樣做過。也許這對我來說並不是最簡單的方式。
第一步是讓你的Person類實現NSCoding協議。基本策略是實現兩種方法來序列化和取消序列化要在會話之間保留的每個對象的實例變量。
#pragma mark NSCoding Protocol
- (void)encodeWithCoder:(NSCoder *)encoder;
{
[encoder encodeObject:[self foo] forKey:@"foo"];
[encoder encodeDouble:[self bar] forKey:@"bar"];
}
- (id)initWithCoder:(NSCoder *)decoder;
{
if (![super init])
return nil;
[self setFoo:[decoder decodeObjectForKey:@"foo"]];
[self setBar:[decoder decodeDoubleForKey:@"bar"]];
return self;
}
實際編寫的對象到磁盤,你可以使用NSArray的writeToFile:
方法,或者,如果你想成爲更明確的瞭解它是如何做使用NSKeyedUnarchiver類。在這兩種情況下,如果您希望在數據文件中包含其他項目(如文件格式編號),則還可以將數組放入另一個數據結構(例如字典)。
Charbonneau先生有正確的想法。 NSCoder
抽象了對象的特定序列化,並讓您只關心需要序列化/反序列化的內容。在-encodeWithCoder:
,你可能想
NSAssert1([encoder allowsKeyedCoding],
@"%@ does not support sequential archiving.",
[self className]);
,因爲不是所有編碼器支持鍵的歸檔。
在-initWithCoder
,你應該送-initWithCoder:
- 不是簡單地-init
- 以super
之前初始化你的對象:
self = [super initWithCoder:decoder];
if (!self) return nil;
// now use the coder to initialize your state
或者,因爲你的對象基本上是一個屬性列表已經,您可以添加類似-[Person plistRepresentation]
:
- (NSDictionary *)plistRepresentation
{
return [NSDictionary dictionaryWithObjectsAndKeys:
[self firstName], @"firstName",
[self lastName], @"lastName",
[NSNumber numberWithInteger:[self age]], @"age", nil];
}
然後,序列化的Person
秒的數組,你可以自己改造成的人他們的plistRepresentation
然後使用-[NSArray writeToURL:atomically:]
。 (當然你也可以使用同樣的NSProperyListSerialization
方法直接。)
它不會通過將writeToFile在這裏工作在我的代碼:原子:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *issueURLsPlist = [documentsDirectory stringByAppendingPathComponent:@"test.plist"];
MyClass * myObject = [[MyClass alloc] init];
NSMutableArray * array = [[NSMutableArray alloc] init];
[array addObject:myObject];
[array writeToFile:issueURLsPlist atomically:YES];
MyClass.h
#import <Foundation/Foundation.h>
@interface MyClass : NSObject <NSCoding>
{
}
@property (nonatomic,copy) NSString * foo;
@property (nonatomic) double bar;
@end
MyClass的。 m
#import "MyClass.h"
@implementation MyClass
- (id)init {
self = [super init];
if (self) {
self.foo = @"test";
self.bar = 0.4f;
}
return self;
}
#pragma mark NSCoding Protocol
- (void)encodeWithCoder:(NSCoder *)encoder;
{
[encoder encodeObject:[self foo] forKey:@"foo"];
[encoder encodeDouble:[self bar] forKey:@"bar"];
}
- (id)initWithCoder:(NSCoder *)decoder;
{
if (![super init])
return nil;
[self setFoo:[decoder decodeObjectForKey:@"foo"]];
[self setBar:[decoder decodeDoubleForKey:@"bar"]];
return self;
}
@synthesize foo;
@synthesize bar;
@end
當我在NSString中使用數組時,方法writeToFile:atomic盟友:工作正常。
刪除那些;的 – 2012-09-10 15:30:46