限制NSArray中的重复条目 [英] Restrict Duplicate entry in NSArray

查看:86
本文介绍了限制NSArray中的重复条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array, which contains some duplicate entries.

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

Firstly, is there any way to restrict duplicate entries when data getting inserted?

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

Secondly, if an array already having duplicate values than in some other way, we can retrieve only unique values from that array, I heard about NSSet about this, but I have no idea how to use it.

推荐答案

不要使用NSSet

您只能在创建时插入元素,并且不能更改创建后包含的元素。

You can only insert elements upon creation and cannot change the elements contained after you have created it.

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

If you want to add and remove objects on the fly, you can use an NSMutableSet.

以下是如何使用 NSSet NSMutableSet ,然后将 NSSet 转换回 NSArray的演示(如果你想这样做):

Here is a demo of how to use it both NSSet and NSMutableSet, then converting the NSSet back to an NSArray (incase you want to do that):

- (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++;
    }
}

这篇关于限制NSArray中的重复条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆