2012-03-18 56 views
2

找不到为什么我的代码无法工作。请帮助别人。无法将我的类的NSMutableArray保存到文件(IOS)

我创建了我自己的类,实现了NSCoding协议。不知道我想念或错误。

这里是节省代码

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"Currency.plist"]; 

Item * item = [[Item alloc] init]; 
item.x = 3; item.y = 5; item.type = (TType) 3; item.isSelected = NO; 

NSMutableArray * array = [[NSMutableArray alloc] init]; 
[array addObject:item]; 

[array fileName atomically:YES] // (Doesn't Save the file ,returns NO); 

这里是我的类的代码 * .H *

#import <Foundation/Foundation.h> 

enum TType 
{ 
    kNone = 0, 
    KFirst = 1, 
    .... 
}; 

@interface Item : NSObject <NSCoding>{ 

} 

@property (nonatomic) int x; 
@property (nonatomic) int y; 
@property (nonatomic) enum TType type; 
@property (nonatomic) BOOL isSelected; 

@end 

.M

@implementation Item 
@synthesize x, y , type , isSelected; 

#pragma mark NSCoding Protocol 

- (void)encodeWithCoder:(NSCoder *)encoder; 
{ 
    [encoder encodeInt32:[self x] forKey:@"x"]; 
    [encoder encodeInt32:[self y] forKey:@"y"]; 
    [encoder encodeInt32:[self type] forKey:@"type"]; 
    [encoder encodeBool:[self isSelected] forKey:@"isSelected"]; 
} 

- (id)initWithCoder:(NSCoder *)decoder; 
{ 
    if (![super init]) 
     return nil; 

    [self setX:[decoder decodeInt32ForKey:@"x"]]; 
    [self setY:[decoder decodeInt32ForKey:@"y"]]; 
    [self setType:(TType)[decoder decodeInt32ForKey:@"color"]]; 
    [self setIsSelected:[decoder decodeBoolForKey:@"isSelected"]]; 

    return self; 
} 

@end 
+0

看到这个帖子http://stackoverflow.com/questions/471830/why-nsuserdefaults-failed-to-save-nsmutabledictionary-in-iphone-sdk – rakeshNS 2012-03-18 08:07:36

回答

4

我想你会发现你在答案:objects conforming to nscoding will not writetofile

即你不能序列您Item类属性列表,因为它不是一个属性列表对象(NSStringNSDataNSArray,或者NSDictionary)。

查看文档writeToFile:atomically:

这种方法递归地验证了所有包含的对象是写出来的文件之前,属性列表对象,并返回NO如果所有的对象都没有属性列表对象,因为生成的文件不会是有效的属性列表。

+2

谢谢:)作为这一工作完全[的NSKeyedArchiver archiveRootObject!数组到文件:文件名] – Buron 2012-03-18 08:14:15

相关问题