限制NSArray中的重复条目

isc*_*ers 4 iphone

我有一个数组,其中包含一些重复的条目.

首先,有没有办法在插入数据时限制重复条目?

其次,如果一个数组已经具有重复值而不是其他方式,我们只能从该数组中检索唯一值,我听说过关于此的NSSet,但我不知道如何使用它.

Bro*_*olf 13

不要使用NSSet.

您只能在创建时插入元素,并且在创建元素后不能更改它们.

如果要动态添加和删除对象,可以使用NSMutableSet.

下面是一个演示如何使用NSSetNSMutableSet,然后将NSSet转换回NSArray(如果你想这样做):

- (void) NSMutableSetPrintTest
{
    NSMutableSet *mutableSet = [[NSMutableSet alloc] init];

    NSLog(@"Adding 5 objects (3 are duplicates) to NSMutableSet");
    NSString *firstString = @"Hello World";
    [mutableSet addObject:firstString];
    [mutableSet addObject:@"Hello World"];
    [mutableSet addObject:@"Goodbye World"];
    [mutableSet addObject:@"Goodbye World"];
    [mutableSet addObject:@"Goodbye World"];

    NSLog(@"NSMutableSet now contains %d objects:", [mutableSet count]);
    int j = 0;
    for (NSString *string in mutableSet) {
        NSLog(@"%d: %@ <%p>", j, string, string);
        j++;
    }

    NSLog(@"Now, if we are done adding and removing things (and only want to check what is in the Set) we should convert to an NSSet for increased performance.");
    NSSet *immutableSet = [NSSet setWithSet:mutableSet];

    NSLog(@"NSSet now contains %d objects:", [immutableSet count]);
    int i = 0;
    for (NSString *string in immutableSet) {
        NSLog(@"%d: %@ <%p>", i, string, string);
        i++;
    }

    [mutableSet release]; mutableSet = nil;

    NSLog(@"Now, if we are done with the sets, we can convert them back to an NSArray:");
    NSArray *array = [immutableSet allObjects];

    NSLog(@"NSArray contains %d objects", [array count]);
    int k = 0;
    for (NSString *string in array) {
        NSLog(@"%d: %@ <%p>", k, string, string);
        k++;
    }
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*ong 9

NSMutableSet 可能是最合乎逻辑的使用方法.

但是,要注意一个集合不维护其元素的顺序(因为根据定义,集合是无序的).

如果这对您来说是个问题,那么您有几个选择:

  • 复制集功能,在每次NSMutableArray调用containsObject:之前调用addObject:(可行,但可能很慢,因为数组有O(n)搜索时间)
  • 使用另一个对象.

如果你选择第二个选项,我建议你看看优秀的CHDataStructures框架,它有一个NSMutableSet被调用的子类CHOrderedSet,它是一个维护插入顺序的集合.(因为它是一个子类,它具有完全相同的API NSMutableSet)


bbu*_*bum 5

如果您听说过NSSet,您是否阅读过文档?API与NSArray类似,非常简单.就像NSArray与NSMutableArray一样,如果需要动态成员资格测试,则可以使用NSMutableSet.