Reputation: 305
I have a mutable array with the following contents:
2012-05-26 23:38:09.606 [8147:f803] log (
{
send = david;
receive = mike;
message = test me;
},
{
send = david;
receive = daddy;
message = test me;
},
{
send = david;
receive = daddy;
message = test me;
}
)
I am finding duplicates values like this:
NSSet *uniquearray = [[NSSet alloc] init];
uniquearray = [[NSSet setWithArray: myArray] valueForKey:@"receive"];
2012-05-26 23:38:09.609 [8147:f803] log (
mike,
daddy
)
But if I want retrieve the message how I can do this? I just want something like take (rebuild an nsarray maybe)
2012-05-26 23:38:09.609 [8147:f803] log (
{
receive = mike,
message = test me;
},
{
receive = daddy
message = test me;
})
Thanks.
Upvotes: 1
Views: 2278
Reputation: 90711
You need to clarify your thinking about what you want. For example, what if the two messages to "daddy" had different content? Which one would you want? Or would you want to keep both?
If you want to keep all unique messages and don't care about the order, you can do:
NSSet* uniqueSet = [NSSet setWithArray:myArray];
If you can require iOS 5.0 or later, you can use NSOrderedSet
to retain the order:
NSOrderedSet* uniqueSet = [NSOrderedSet orderedSetWithArray:myArray];
If you only want to keep one message from each receiver, you can do something like this:
NSMutableArray* uniqueArray = [NSMutableArray array];
NSMutableSet* seen = [NSMutableSet set];
for (NSDictionary* dict in myArray)
{
NSString* receiver = [dict objectForKey:@"receiver"];
if (![seen containsObject:receiver])
{
[uniqueArray addObject:dict];
[seen addObject:receiver];
}
}
As an aside, you should not name a variable uniquearray
when it's not an array but a set. Second, this code:
NSSet *uniquearray = [[NSSet alloc] init];
uniquearray = [[NSSet setWithArray: myArray] valueForKey:@"receive"];
Allocates one empty set and then throws away the pointer to it, replacing the pointer with a pointer to a different set. The first object is entirely wasted. If you're not using ARC, it's also leaked.
Upvotes: 3
Reputation: 337
You might want to use NSDictionary where I know you can make an array using keysOfEntriesPassingTest or other methods that help you work with the keys.
Upvotes: 0