将NSMutableArrays保存到pList

时间:2011-08-02 03:15:13

标签: xcode plist

我正在尝试将NSMutableArray存储到pList中,但是当我检查我的data.pList时,里面没有任何值。知道为什么吗?

-(void)run
{
Global *myGlobal = [Global sharedGlobal];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];

NSMutableDictionary *category = [[NSMutableDictionary alloc]init];
NSMutableDictionary *totalCategory = [[NSMutableDictionary alloc]init];
for (int i = 0 ; i < [myGlobal.categoryArray count];i++){
    Category * c = [categoryArray objectAtIndex:i];

    [category setObject:c.name forKey:@"category"];

    [totalCategory setObject:category forKey:@"allCategory"];

    NSMutableDictionary *stock = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    [stock writeToFile:path atomically:YES];
}
if( totalCategory==nil ){
    NSLog(@"failed to retrieve dictionary from disk");
}
}

2 个答案:

答案 0 :(得分:0)

这两行没有意义。第一行从path读取字典到stock,第二行将其写回。没有添加任何内容stock

NSMutableDictionary *stock = [NSMutableDictionary dictionaryWithContentsOfFile:path];
[stock writeToFile:path atomically:YES];

答案 1 :(得分:0)

保存到pList时,你应该尝试这样做。

[totalCategory writeToFile:path atomically:YES];

这是一个如何正常工作的例子


+ (void) saveParams:(int)kotuc one:(NSNumber*)one two:(NSNumber*)two three:(NSNumber*)three four:(NSNumber*)four five:(NSNumber*)five six:(NSNumber*)six seven:(NSNumber*)seven eight:(NSArray*)eight{

    NSString *path = [self getNSPath];
    NSDictionary* dw = [[NSDictionary alloc] initWithContentsOfFile:path];
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];

    NSArray *keys = [[NSArray arrayWithObjects:@"one", @"two", @"three", @"four", @"five", @"six",@"seven", @"eight",nil] retain];
    NSArray *objects = [[NSArray arrayWithObjects:one, two, three, four, five, six, seven, eight, nil] retain];


    NSMutableDictionary *subDict = [[NSMutableDictionary alloc] initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys];


    ////save old
    [dict setDictionary:dw];
    ////save new
    [dict setObject:subDict forKey:[NSString stringWithFormat:@"%i", kotuc]];    // 
    //write to file
    [dict writeToFile:path atomically:YES];


    [dw release];
    [dict release];
    [subDict release];
    [keys release];
    [objects release];
}