2012-03-18 57 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

相關問題