2014-07-10 135 views
-1

我试着去我的NSMutableArray保存到磁盘,阵列 看起来:为什么我的NSMutableArray不能保存

 self.tableData = [[NSMutableArray alloc] initWithObjects: 
          [[Cell alloc] initWithName:@"dawdw" andImage:@"dwddw" andDescription:@"dawdw" andTypes:@"dawwd dawwd" andforWho:@"dwaadw"], 
          [[Cell alloc] initWithName:@"Kabanos" andImage:@"spodwwdwdrt.jpg" andDescription:@"dwdw" andTypes:@"dwdw dww" andforWho:@"dawwd"], 
          [[Cell alloc] initWithName:@"dwwd" andImage:@"dwwd" andDescription:@"dwwd" andTypes:@"wdwd daww" andforWho:@"dadawwa"],nil]; 


//execution 
[self writeToPlist:@"fav.txt" withData:self.tableData]; 


- (void) writeToPlist: (NSString*)fileName withData:(NSMutableArray *)data 
{ 
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:fileName]; 

    [data writeToFile:finalPath atomically: YES]; 
} 

//loading 
- (NSMutableArray *) readFromPlist: (NSString *)fileName { 
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:fileName]; 

    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:finalPath]; 

    if (fileExists) { 
     NSMutableArray *arr = [[NSMutableArray alloc] initWithContentsOfFile:finalPath]; 
     return arr; 
    } else { 
     return nil; 
    } 
} 

//load 
self.tableData = [self readFromPlist:@"fav.txt"]; 

和可悲的是最后资料表是空的,我试过一些方法来节省NSMutableArray的,但我不能弄清楚如何。

+1

阅读'的NSArray将writeToFile文档:原子:'。看看它可以保存的对象的类型。 – rmaddy

+0

所以任何其他想法保存和阅读nsmutablearray? – karek

+0

你在做什么只是保存和读取数组。问题是数组中的数据。要么更改数组数据以便可保存,要么搜索保存包含自定义对象的数组。 – rmaddy

回答

1

当你的可变数组包含自定义对象时,操作系统将不知道如何对它们进行编码和解码。 自定义类可以通过将以下函数添加到您的类中进行编码和解码。 确保类符合NSCoding

- (id)initWithCoder:(NSCoder *)decoder { 
    self = [super init]; 
    if (!self) { 
     return nil; 
    } 

    self.var1 = [decoder decodeObjectForKey:@"var1"]; 
    self.var2 = [decoder decodeObjectForKey:@"var2"]; 
    .. and so on 
    return self; 
} 

- (void)encodeWithCoder:(NSCoder *)encoder { 
    [encoder encodeObject:self.var1 forKey:@"var1"]; 
    [encoder encodeObject:self.var2 forKey:@"var2"]; 
} 

我们存档 -

[NSKeyedArchiver archiveRootObject:<array of objects> toFile:@"/path/to/archive"]; 

要解除封存

[NSKeyedUnarchiver unarchiveObjectWithFile:@"/path/to/archive"]; 

H个

0

从文档:

如果阵列中的内容都是属性列表对象(的NSStringNSData的的NSArray,或的NSDictionary对象),通过 写入的文件方法可用于使用类方法 arrayWithContentsOfFile:或实例方法 initWithContentsOfFile:来初始化新数组。这种方法递归地验证了所有 所包含的对象是写出来的 文件之前,属性列表对象,并返回NO如果所有的对象都没有属性列表对象, 从得到的文件将不会是一个有效的财产清单。

(重点煤矿)

你可以把它变成/从NSData或任何其他财产清单对象上的Cell类的方法,把塔到阵列中,然后将其保存。

相关问题