无法将我的类的NSMutableArray保存到文件(IOS)

时间:2012-03-18 07:56:11

标签: objective-c ios serialization nsmutablearray

无法找出我的代码无效的原因。请帮助别人。

我创建了自己的类,实现了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

1 个答案:

答案 0 :(得分:4)

我想你会在objects conforming to nscoding will not writetofile

找到答案

即。您无法将Item类序列化到属性列表,因为它不是属性列表对象(NSStringNSDataNSArray或{{1} })。

请参阅writeToFile:atomically:的文档:

  

此方法在写出文件之前以递归方式验证所有包含的对象是属性列表对象,如果所有对象都不是属性列表对象,则返回NSDictionary,因为生成的文件不是有效的属性列表