无法找出为什么我的代码不起作用。请帮助某人。
我创建了自己的类,实现了 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
我想你会在以下位置找到答案:符合 nscoding 的对象不会 writetofile https://stackoverflow.com/questions/5352032/objects-conforming-to-nscoding-will-not-writetofile
即你无法序列化你的Item
类到属性列表,因为它不是属性列表对象(NSString
, NSData
, NSArray
, or NSDictionary
).
请参阅文档writeToFile:atomically: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/writeToFile:atomically::
该方法在写出文件之前递归地验证所有包含的对象是否都是属性列表对象,并返回NO
如果所有对象都不是属性列表对象,因为生成的文件将不是有效的属性列表。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)