无法将我的类的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); 

这是我class级的代码 * .h *

 #import  enum TType { kNone = 0, KFirst = 1, .... }; @interface Item : NSObject { } @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 

我想你会找到你的答案: 符合nscoding的对象不会写

即,您不能将Item类序列化为属性列表,因为它不是属性列表对象( NSStringNSDataNSArrayNSDictionary )。

请参阅writeToFile:atomically:的文档writeToFile:atomically: ::

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