如何以编程方式从iOS中的plist中检索数据?

时间:2013-03-16 05:07:01

标签: ios date compare plist

我想在我的plist中比较两个日期,当前日期和日期。如果我的plist中的当前日期和日期相等,那么我想显示一些东西。有可能吗?

plist中的层次结构是Array-> Dictionary->(对象是被视为一个数组的联系人,所有对象的键应该是相同的,它是一个字符串)。我想将密钥与当前日期进行比较。

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码。

NSString *path = [[NSBundle mainBundle] pathForResource:@"EventAddress" ofType:@"plist"]; 
NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

NSArray* allmyKeys = [myDictionary  allValues];
NSLog(@"%@", allmyKeys);
NSLog(@"%@", [[allmyKeys objectAtIndex:0] objectAtIndex:0]);

从plis获取日期 你的plist日期应该包含:

<date>2011-12-13T00:00:00Z</date>

并从NSDictionary获取日期:

NSDate *eventDate = [myDictionary objectForKey:@"date"];

并比较两个日期使用:

switch ([[NSDate date] compare:eventDate]){
 case NSOrderedAscending:
      NSLog(@"NSOrderedAscending");
break;
case NSOrderedSame:
      NSLog(@"NSOrderedSame");
break;
case NSOrderedDescending:
     NSLog(@"NSOrderedDescending");
break;
}

答案 1 :(得分:0)

要满足这一要求“plist中的层次结构将是Array-&gt; Dictionary-&gt ;;(对象将被视为一个数组,并且所有对象的键应该相同,并且它是一个字符串).i want要将密钥与当前日期进行比较,“您需要按照以下步骤进行操作

  1. 从.plist文件中获取所有数组
  2. 获取当前数组对象中的所有词典
  3. 获取当前Dictionaries对象中的所有键
  4. 使用NSComparisonResult

    比较您的KEY和当前日期
    NSDate *date1 = < YOUR CURRENT DATE HERE > ;
    NSString *plistFilePath  = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"SyncAuditMainScreen.plist"];
    
    NSArray *array = [NSArray arrayWithContentsOfFile:plistFilePath];
    for(int i=0;i<[array count];i++)
    {
        NSMutableDictionary *details=[array objectAtIndex:i];
        NSArray *allmyKeys = [details allKeys];
        for(NSString *key in allmyKeys)
        {
            NSLog(@"KEY: %@",key);
            NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
            [formatter setDateFormat:< YOUR FORMAT OF DATE >];
            NSDate *date2 = [formatter dateFromString:key];
            NSComparisonResult result = [date1 compare:date2];
            if(result==NSOrderedSame)
                NSLog(@"Key and current date are same");
        }
    }
    
相关问题