0

我正在创建一个允许您记录棋盘游戏的应用程序。我将我的日志存储在一个 plist 中,我试图弄清楚如何附加 plist。我想我理解逻辑,但我无法将其放入代码中。

我的 plist 看起来像这样:

列表

现在我正在尝试这样的事情,但我相信它只会覆盖 plist 文件而不是附加

//get path for root directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

NSLog(@"paths: %@",paths);

//get path for documents directory
NSString *documentsPath = [paths objectAtIndex:0];
NSLog(@"documentsPath: %@",documentsPath);

//get the path for logs.plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"logs.plist"];


//create dictionary with values
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:myLogTitle, name, players, myNotes, nil] forKeys:[NSArray arrayWithObjects:@"Log Title",@"Name",@"Players","Notes", nil]];

//write out data
 [plistDict writeToFile:plistPath atomically:YES];

任何帮助将非常感激。

4

1 回答 1

0

像这样试试

NSString *path = [[NSBundle mainBundle] pathForResource: @"data" ofType: @"plist"]; 
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: path];
NSLog(@"dictbeforeAppending..%@",dict);

//getting Previous Array.....
NSMutableArray *prevArray = [[NSMutableArray alloc]init];
prevArray = [[dict valueForKey:@"Root"] valueForKey:@"Logs"];
NSLog(@"prevArray..%@",prevArray);

// Add new stuff to old stuff.....

NSMutableArray *players =[[NSMutableArray alloc]initWithObjects:@"NewPlayer1",@"Newplayer2",@"Newplayer3", nil];//1
NSDictionary *newObject = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"Logtiltle2", @"Krish", players, @"it will be more fun", nil] forKeys:[NSArray arrayWithObjects:@"Log Title",@"Name",@"Players",@"Notes", nil]];//2

NSMutableArray *newArray = [[NSMutableArray alloc]init];
[newArray addObject:newObject];
for (int i=0;i<[prevArray count];i++){
    [newArray addObject:[prevArray objectAtIndex:i]];
}

//set all values for Plist......
NSMutableDictionary *allItemsDict = [[NSMutableDictionary alloc]init];
NSMutableArray *Logs = [[NSMutableArray alloc]initWithArray:newArray];
[allItemsDict setObject:Logs forKey:@"Logs"];

NSMutableDictionary *Root = [[NSMutableDictionary alloc]init];
[Root setObject:allItemsDict forKey:@"Root"];

// Now, write to the plist:
[Root writeToFile:path atomically:YES];

NSDictionary *dictafterAppending = [NSDictionary dictionaryWithContentsOfFile: path];
NSLog(@"dictafterAppending..%@",dictafterAppending);

如果您卡在任何地方,请告诉我伙计...

于 2013-05-13T09:57:39.477 回答