找不到爲什麼我的代碼無法工作。請幫助別人。無法將我的類的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
看到這個帖子http://stackoverflow.com/questions/471830/why-nsuserdefaults-failed-to-save-nsmutabledictionary-in-iphone-sdk – rakeshNS 2012-03-18 08:07:36