比较NSDictionary中的字符串

时间:2012-03-27 18:57:17

标签: objective-c compare nsdictionary

我有一个从plist格式化的NSDictionary:

    <plist version="1.0">
<dict>
    <key>Contents</key>
        <array>
            <dict>
                <key>date</key>
                <string>20110323</string>
                <key>name</key>
                <string>update.zip</string>
                <key>url</key>
                <string>http://intranet.webaddress.com/mobile/ipad/</string>
            </dict>
            <dict>
                <key>date</key>
                <string>20120323</string>
                <key>name</key>
                <string>plns.galleryy.zip</string>
                <key>url</key>
                <string>http://intranet.webaddress.com/mobile/ipad/</string>
            </dict>
        </array>
</dict>
</plist>

我需要遍历NSDictionary并获取日期字符串大于我提供的任何名称值。所以伪代码(尽管工作)会是这样的:

NSMutableArray *urls = [NSMutableArray arrayWithCapacity:1];

NSMutableDictionary *capabilities;
capabilities = [[myData libraryDictionary] valueForKey:@"Contents"];

for (int i=0; i<[myData libraryCount]; i++) {
    NSString *value = [[capabilities valueForKey:@"date"] objectAtIndex:i];

    if ([value compare: @"20120323"] == NSOrderedSame)
    {
        NSLog(@"Equal");
        NSLog(@"%@",value);
        NSString *saveValue = [[capabilities valueForKey:@"name"] objectAtIndex:i];
        [urls addObject:saveValue];
        NSLog(@"%@",saveValue);
    }
    else 
    {
        NSLog(@"Not Equal");
    }
}

然后我只会下载日期早于我提供日期的文件。在这个简单的例子中,我只会将plns.galleryy.zip添加到我的可变数组中。

任何人都可以帮我解决这个问题吗?上面的工作,但这是最好的方式?

注意:[myData libraryDictionary]是我的字典,正在为其他目的正常阅读。

非常感谢

1 个答案:

答案 0 :(得分:0)

您需要从日期字符串中创建NSDate:

NSDateFormatter *format = [NSDateFormatter new];
[format setDateFormat:@"YYYYMMDD"];

foreach (NSString *dateStr in dictionary)
{
    NSDate *date = [format dateFromString:dateStr];

    if ([date compare:compareDate] >= 0)
    {
        // download the new file
    }
}