在目标 c 中编辑 plist

Posted

技术标签:

【中文标题】在目标 c 中编辑 plist【英文标题】:Edit plist in objective c 【发布时间】:2011-11-30 17:09:06 【问题描述】:

我有一个 plist 文件,我想编辑这个文件,但是 NSDictionary 中的 setObject() 不起作用,我的代码是:

NSString *documentsDirectoryConf = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString *pathConf = [documentsDirectoryConf stringByAppendingPathComponent: @"Test.plist"];
NSMutableDictionary *infoConf = [[NSMutableDictionary alloc] initWithContentsOfFile:pathConf];
NSMutableArray* defaultIm = [infoConf objectForKey:@"DatosDescargas"];
NSMutableDictionary *banners = [defaultIm objectAtIndex:0];

NSInteger numI = (int)[banners objectForKey:@"NumImages"]; 
NSInteger numD = (int)[banners objectForKey:@"DownloadImges"]; 

NSLog(@"Numero total de Imagenes: %i",numI);
NSLog(@"Numero de Imagenes descargadas: %i",numD);

**numI = 7206;
numD = 5;**

[banners setObject:(id)numI forKey:@"NumImages"];
[banners setObject:(id)numD forKey:@"DownloadImges"];

[defaultIm replaceObjectAtIndex:0 withObject:banners];

[infoConf setObject:defaultIm forKey:@"DatosDescargas"];

pathConf = [documentsDirectoryConf stringByAppendingPathComponent: @"Test.plist"];

//save content to the documents directory
[infoConf writeToFile:[pathConf stringByExpandingTildeInPath] 
           atomically:TRUE];

defaultIm = [infoConf objectForKey:@"DatosDescargas"];
banners = [defaultIm objectAtIndex:0];

numI = (int)[banners objectForKey:@"NumImages"]; 
numD = (int)[banners objectForKey:@"DownloadImges"]; 

NSLog(@"Numero total de Imagenes: %i",numI);
NSLog(@"Numero de Imagenes descargadas: %i",numD);

在我的控制台中可能看到不要编辑任何值:

2011-11-30 17:55:07.879 Catalogo-V1[5905:207] Numero total de Imagenes: 0
2011-11-30 17:55:07.880 Catalogo-V1[5905:207] Numero de Imagenes descargadas: 0
2011-11-30 17:55:07.880 Catalogo-V1[5905:207] Numero total de Imagenes: 0
2011-11-30 17:55:07.881 Catalogo-V1[5905:207] Numero de Imagenes descargadas: 0

而且我的文件有这种格式,需要修改第二个字典,然后修改一个数组和第一个字典:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>DatosDescargas</key>
    <array>
        <<dict>
            <key>NumImages</key>
            <integer>0</integer>
            <key>DownloadImges</key>
            <integer>0</integer>
        </dict>
    </array>
</dict>
</plist>

【问题讨论】:

【参考方案1】:

您需要将其转换为 NSNumber

[NSNumber numberWithInt:numI];

然后你可以检索它:

numI = [[banners objectForKey:@"NumImages"] intValue]; 

【讨论】:

以上是关于在目标 c 中编辑 plist的主要内容,如果未能解决你的问题,请参考以下文章

plist 捆绑版本值

XCode 编辑项目设置与编辑活动目标

在 NSDictionary 中编辑 plist

在 Xcode 中编辑 plist

在 Linux 中编辑 PLIST 中的值

从本地 bash 脚本文件夹中编辑 plist