在NSMutableDictionary中查找字典并将其删除

时间:2011-03-05 17:08:42

标签: objective-c ios4 nsdictionary

    <plist version="1.0">
<dict>
    <key>Rows</key>
    <array>
        <dict>
            <key>FavTitle</key>
            <string>AppliedVersion</string>
            <key>SaveName</key>
            <string>122.pdf</string>
            <key>duh</key>
            <string>Favourited</string>
        </dict>
        <dict>
            <key>FavTitle</key>
            <string>Test Eng. Version</string>
            <key>SaveName</key>
            <string>dsds.pdf</string>
            <key>duh</key>
            <string>Favourited</string>
        </dict>
    </array>
</dict>
</plist>

尝试使用此功能删除内容:

NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"Favourites.plist"];
    NSMutableDictionary *rootDict = [[NSMutableDictionary alloc] initWithContentsOfFile:writablePath];
    NSMutableDictionary *newFav = [NSMutableDictionary dictionaryWithObjectsAndKeys: selectedFavTitle, @"FavTitle", @"Favourited", @"duh", selectedSaveName, @"SaveName", nil];
    [[rootDict objectForKey:@"Rows"] removeObjectIdenticalTo:newFav];  
    [rootDict writeToFile:writablePath atomically: YES];

它一直在努力! 缺陷是:

[[rootDict objectForKey:@"Rows"] removeObjectIdenticalTo:newFav]; 

因为它不会删除匹配的对象

2 个答案:

答案 0 :(得分:1)

NSMutableDictionary *newFav = [NSMutableDictionary dictionaryWithObjectsAndKeys: selectedFavTitle, @"FavTitle", @"Favourited", @"duh", selectedSaveName, @"SaveName", nil];

此行创建NSMutableDictionary的新实例。因此,当您调用removeObjectIdenticalTo:时,它与任何内容都不匹配,因为新实例与rootDict中的实例不是同一个对象。

您可以使用filterUsingPredicate:过滤掉不需要的对象,也可以手动循环rootDict以手动查找和删除对象。

答案 1 :(得分:0)

我的猜测是编码问题。您没有告诉我们在保存此plist文件时指定了哪种编码,而您没有明确指定这样的编码:

<?xml version="1.0" encoding="UTF-8"?>