Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement "group by values" in NSMutableArray?

I am using NSMutableArray. I want to fetch the values by date like we do in SQL group by "log_date".

logMuArray (
        {
        "log_currenttime" = "4:30pm";
        "log_date" = "11.12.2011";
        "log_duration" = "1:30";
    },
        {
        "log_currenttime" = "4:33pm";
        "log_date" = "11.12.2011";
        "log_duration" = "2:21";
    },
        {
        "log_currenttime" = "4:40pm";
        "log_date" = "11.12.2011";
        "log_duration" = "5:30";
    },
        {
        "log_currenttime" = "7:30pm";
        "log_date" = "12.12.2011";
        "log_duration" = "1:30";
    },
        {
        "log_currenttime" = "7:33pm";
        "log_date" = "12.12.2011";
        "log_duration" = "2:21";
    },
        {
        "log_currenttime" = "7:40pm";
        "log_date" = "12.12.2011";
        "log_duration" = "5:30";
    },
        {
        "log_currenttime" = "07:16pm";
        "log_date" = "19.12.2011";
        "log_duration" = "0:07";
    },
        {
        "log_currenttime" = "7:31pm";
        "log_date" = "19.12.2011";
        "log_duration" = "0:04";
    },
        {
        "log_currenttime" = "7:33pm";
        "log_date" = "19.12.2011";
        "log_duration" = "0:03";
    },
        {
        "log_currenttime" = "7:33pm";
        "log_date" = "19.12.2011";
        "log_duration" = "0:06";
    },
        {
        "log_currenttime" = "7:35pm";
        "log_date" = "19.12.2011";
        "log_duration" = "0:05";
    }
)

**So, I have just performed....

 NSLog(@"logMuArray %@",[logMuArray valueForKey:@"log_date"]);

But I want to fetch the UNIQUE dates only.** I have thought about NSPredicate or Mutable Set etc...

logMuArray (
    "11.12.2011",
    "11.12.2011",
    "11.12.2011",
    "12.12.2011",
    "12.12.2011",
    "12.12.2011",
    "19.12.2011",
    "19.12.2011",
    "19.12.2011",
    "19.12.2011",
    "19.12.2011"
)

Thanks in advance.....

EDIT:

I have also heared about "@distinctUnionOfObjects"

......

like image 374
Arpit B Parekh Avatar asked Dec 20 '11 06:12

Arpit B Parekh


1 Answers

Shanti's answer is close. You want to use the Key-Value Coding collection operator @distinctUnionOfObjects. Place the operator immediately preceding the key which you want it to affect, as if it is a part of the key path you are accessing:

[logMuArray valueForKeyPath:@"@distinctUnionOfObjects.log_date"]

Notice the use of valueForKeyPath:, not valueForKey: The former is a method in the Key-Value Coding protocol, and allows accessing arbitrary depth of attributes. The key path is an NSString made up of dot-separated keys. The result of each key lookup is used in turn to access the next key (starting with the original receiver); by default, valueForKey: is simply called at each step.

like image 148
jscs Avatar answered Oct 23 '22 20:10

jscs