将 NSArray 写入 plist 文件

Write NSArray to plist file

我有一个获取plist文件数据的代码和一个将数据写入plist文件的代码。现在事情是,它将读取的数据添加到一个数组中(参见图像)。 我想要它在不同的阵列中(见绿色图像)

这是我的代码:

- (void)WriteData {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"MuziekList.plist"];

if ([fileManager fileExistsAtPath:path] == NO) {
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"MuziekList" ofType:@"plist"];
    [fileManager copyItemAtPath:resourcePath toPath:path error:&error];
}
//_______________________________________________________________________________________________________________
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

//load from savedStock example int value
NSArray *NummerTexts;
NummerTexts = [savedStock objectForKey:@"Nummers"];
NSString *NummerTextsR = [[NummerTexts valueForKey:@"description"] componentsJoinedByString:@" - "];

NSArray *ArtiestTexts;
ArtiestTexts = [savedStock objectForKey:@"Artiesten"];
NSString *ArtiestTextsR = [[ArtiestTexts valueForKey:@"description"] componentsJoinedByString:@" - "];
//_______________________________________________________________________________________________________________

NSUserDefaults *CurrentVideoNummerResult = [NSUserDefaults standardUserDefaults];
NSString *CurrentVideoNummer = [CurrentVideoNummerResult stringForKey:@"CurrentVideoNummer"];

NSUserDefaults *CurrentVideoArtiestResult = [NSUserDefaults standardUserDefaults];
NSString *CurrentVideoArtiest = [CurrentVideoArtiestResult stringForKey:@"CurrentVideoArtiest"];

/*
NSUserDefaults *CurrentVideoIDResult = [NSUserDefaults standardUserDefaults];
NSString *CurrentVideoID = [CurrentVideoIDResult stringForKey:@"CurrentVideoID"];
*/

NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
NSMutableArray *newArray2 = [[NSMutableArray alloc] init];

newArray = [NSMutableArray arrayWithObjects:CurrentVideoNummer, NummerTextsR, nil];
[plist setObject:newArray forKey:@"Nummers"];


newArray2 = [NSMutableArray arrayWithObjects:CurrentVideoArtiest, ArtiestTextsR, nil];
[plist setObject:newArray2 forKey:@"Artiesten"];

[plist writeToFile:path atomically:YES];
}

点击link查看图片

https://www.dropbox.com/sh/wrk8h8cnwye8myx/AADl4omkGdl3S4ESXv6NbymVa?dl=0

你的提问和问题比较混乱。也许这会有所帮助:

您的代码读取当前数组 (NummerTexts),将该数组展平为单个字符串 (NummerTextsR),获取第二个字符串 (CurrentVideoNummer),然后构建两个-元素数组(newArray).

你的问题似乎是为什么你得到一个二元素数组...?

如果您不想展平您的原始数组,请不要这样做,只需制作它的可变副本,例如:

NSMutableArray *existingTexts = [[NummerTexts valueForKey:@"description"] mutableCopy];

添加新元素:

[existingTexts addObject:currentVideoNummer];

然后像现在一样写回去。

HTH

顺便说一句,不要以大写字母开头局部变量名,这违反了惯例,这就是为什么你的问题中突出显示的语法都是错误的。