0
[myItem enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if (obj isEqualToString:@"someString" > 1) { // not correct syntax
        self.someLabel.text = [self.someLabel.text stringByAppendingString:[NSString stringWithFormat:@"\t\t%@\n", obj]];
    }
}];

I am trying to check if obj is equal to "someString". And if "someString" is displayed more than one I would like to remove it from the obj.

"itemOne"

"otherItem"

"someString"

"someString" <- remove

"someString" <- remove

I am having issues dynamically doing this within the loop in objective c.

Machavity
  • 30,841
  • 27
  • 92
  • 100

5 Answers5

0

An easier solution is to convert the array to an ordered set and then back to an array. This will remove duplicates.

CrimsonChris
  • 4,651
  • 2
  • 19
  • 30
0

try like this,

UniqArray = [CurrentArray valueForKeyPath:@"@distinctUnionOfObjects.self"];

or

NSArray *UniqArray = [[NSOrderedSet orderedSetWithArray:CurrentArray]allObjects];

or

NSArray *UniqArray = [[NSSet setWithArray:CurrentArray] allObjects]
Balu
  • 8,470
  • 2
  • 24
  • 41
0

You can convert it to an ordered set, which removes the duplicates, then convert it back to an array.

// remove duplicates
NSOrderedSet *myItemSet = [NSOrderedSet orderedSetWithArray:myItem];

// convert it back to NSArray
NSArray *myItemArrayWithoutDuplicates = myItemSet.array;
edwardmp
  • 6,339
  • 5
  • 50
  • 77
0

You can use continue statement for displaying the data without dublicates

[myItem enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if ([obj isEqualToString:@"someString"]) { 
        self.someLabel.text = [self.someLabel.text stringByAppendingString:[NSString stringWithFormat:@"\t\t%@\n", obj]];
     continue;
    }
}];

This will exist from current iteration after value assigned in label.

If you want to delete the dublicate objects. If Order of Items does not matter...

NSArray *itemsArray = [[NSSet setWithArray: myItem] allObjects];

If order of items matter..

 NSMutableArray *uniqueItems = [NSMutableArray array];
for (id item in myItem)
    if (![uniqueItems containsObject:item])
        [uniqueItems addObject:item];

Hope it helps you..

Vidhyanand
  • 5,369
  • 4
  • 26
  • 59
0

Swift 5

let array = ["itemOne", "otherItem", "someString", "someString", "someString"]

print(array) // "itemOne", "otherItem", "someString", "someString", "someString"]

var set = Set<String>()
for item in array{
    set.insert(item)
}

print(set) // ["otherItem", "someString", "itemOne"]
Mithra Singam
  • 1,905
  • 20
  • 26