0

I have a array of custom UIView objects with 2 or more objects having same center and I have to construct another array from it with distinct centers. What is the best way to do it?

I tried with below piece of code but it does not work.

self.distinctObjects = [NSMutableArray arrayWithCapacity:iAllObjects.count];

for (MyCustomView *customView in iAllObjects)
{
     BOOL hasDuplicate = [[self.distinctObjects filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF.center == %@", customView.center]] count] > 0;

     if (!hasDuplicate) {
                [self.distinctObjects addObject:customView];
     }
}
Abhinav
  • 37,684
  • 43
  • 191
  • 309

2 Answers2

1

You can't use struct's (in your case center is a CGPoint) in NSPredicate. Also comparing floating-point values directly isn't a good idea. You should follow this answer. Just replace [annotation coordinate].latitude with myView.center.x, [annotation coordinate].longitude with myView.center.y, and so on. It should be easy.

BTW your code has O(n^2) complexity, but maybe that's not a problem if the array is small.

Community
  • 1
  • 1
Arek Holko
  • 8,966
  • 4
  • 28
  • 46
  • I have fixed this. Please see my code (in answer below). I am looping once in the main array and checking for duplicates in a temp array. Do you think there can be a better way of doing it? – Abhinav Oct 13 '13 at 23:03
  • `NSSet` comes to my mind mind, when thinking about checking for duplicates. [Here](http://stackoverflow.com/a/5719584/1990236) you've got a similar problem. – Arek Holko Oct 14 '13 at 07:32
0

I fixed this with below piece of code:

NSMutableArray *uniqueCenters = [NSMutableArray arrayWithCapacity:iAllObjects.count];
self.distinctObjects = [NSMutableArray arrayWithCapacity:iAllObjects.count];

for (MyCustomView *customView in iAllObjects)
{
    if (![uniqueCenters containsObject:[NSValue valueWithCGPoint:customView.center]]) {
        [uniqueCenters addObject:[NSValue valueWithCGPoint:customView.center]];

        [self.beacons addObject:customView];
    }
}
Abhinav
  • 37,684
  • 43
  • 191
  • 309