Sam
Sam

Reputation: 902

Merging objects(NSDictionary) of an NSArray having common data

Following is my database structure :

(
  {
      NSDate
      Name
  },
  {
      NSDate
      Name
  }

);

Want to convert the above NSArray into following structure :

   (
      {
          Date
          Time
               (

               )
          Name 
               (

               )              
      },
      {
          Date
          Time
               (

               )
          Name 
               (

               )
      }

    );

Example :

Initially Sorted Array

Date             Name

1-7-2011 10.00   A1
2-7-2011 2.00    A2
2-7-2011 2.00    A3
2-7-2011 3.00    A4

Output :

Date        Time       Name
1-7-2011    10.00       A1

                        A2
            2.00        A3
2-7-2011                
            3.00        A4

In sort want to merge events having same common factors & add common factor only once.So whether it is possible to implement the above thing using predefine iOS framework functions? Thanx in advance.

Upvotes: 1

Views: 293

Answers (1)

Mihai Fratu
Mihai Fratu

Reputation: 7663

This should do it

NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];

for (NSDictionary *item in yourArray) {
    NSDate *date = [item objectForKey:@"date"];

    [dateFormater setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString = [dateFormater stringFromDate:date];

    [dateFormater setDateFormat:@"hh:mm"];
    NSString *timeString = [dateFormater stringFromDate:date];

    if ([dictionary objectForKey:dateString]) {
        if ([dictionary objectForKey:timeString]) {
            [[[dictionary objectForKey:dateString] objectForKey:timeString] setObject:[item objectForKey:@"name"] forKey:@"name"];
        }
        else {
            NSMutableDictionary *timeDictionary = [NSMutableDictionary dictionaryWithObject:[item objectForKey:@"nam"] forKey:@"name"];
            [[dictionary objectForKey:dateString] setObject:timeDictionary forKey:timeString];
        }
    }
    else {
        NSMutableDictionary *timeDicationary = [NSMutableDictionary dictionaryWithObject:[item objectForKey:@"name"] forKey:@"name"];
        NSMutableDictionary *dateDictionary = [NSMutableDictionary dictionaryWithObject:timeDictionary forKey:timeString];
        [dictionary setObject:dateDictionary forKey:dateString];
    }
}

[dateFormater release];

Upvotes: 1

Related Questions