需要帮助快速搜索iOS属性列表(plist)的值



我目前在我的iOS项目中有一个plist文件,当更新可用时从网络下载,它包含新闻文章列表以及图像。

应用程序在iPhone上缓存图像以供离线访问,我目前正在尝试编写一个函数,该函数将每隔一段时间清理缓存文件。

目前我有这段代码,它在临时文件夹中查找图像,然后删除它们,但是对于每个图像,我希望它检查文件名是否存在作为删除前存储为NSDictionary的plist中的值,但是我不确定一个快速的方法来搜索NSDictionary,而不需要for语句。

有什么建议就太好了。

 NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:TMP error:nil];
    if (files == nil) {
        // error...
        NSLog(@"no files found");
    }
    for (NSString *file in files) {
        NSString *uniquePath = [TMP stringByAppendingPathComponent: file];
        if([file rangeOfString: @".png" options: NSCaseInsensitiveSearch].location != NSNotFound)
        {
            NSLog(@"%@", file);   

            if ([[NSFileManager defaultManager] removeItemAtPath: uniquePath error: NULL]  == YES)
                NSLog (@"Remove successful");
            else
                NSLog (@"Remove failed");
        }
    }  

编辑

我目前添加了这个,不确定这是否是最好的方法,但它是有效的。

 NSArray *newsArray = [self.newsData allValues];
 // Convert the Array into a string
 NSString *newsString = [newsArray description];
 // Perform Range Search.
 NSRange range;
 range = [newsString rangeOfString : filename];
 if (range.location != NSNotFound) {
    NSLog(@"The file exists in the plist %@", filename);
 } else {
     // Delete the file
 }

您可以使用NSPredicate减少数组,使其只包含您感兴趣的对象,然后快速遍历您希望删除的对象。像这样:

NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:TMP error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] '.png'"];
NSArray *filteredArray = [files filteredArrayUsingPredicate:thePredicate];
for (NSString *file in filteredArray) {
    NSString *uniquePath = [TMP stringByAppendingPathComponent:file];
     if ([[NSFileManager defaultManager] removeItemAtPath: uniquePath error: NULL])
            NSLog (@"Remove successful");
     else
        NSLog (@"Remove failed");
}

这将意味着for循环只在您感兴趣的对象上循环。

因为你不关心plist或文件夹中的文件顺序,你显然不会有重复,使用NSSet而不是NSArray,然后使用相交方法(intersectsSet:)来找到交集。

最新更新