如何在NSMutableArray中删除重复的值 [英] how to remove duplicate value in NSMutableArray

查看:109
本文介绍了如何在NSMutableArray中删除重复的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NSMutableArray扫描wifi信息,但是几乎没有重复的值出现,所以我尝试使用以下代码,但仍然得到重复的值,

  if([scan_networks count]> 0)
{
NSArray * uniqueNetwork = [[NSMutableArray alloc] initWithArray:[[NSSet setWithArray:scan_networks] allObjects]];
[scan_networks removeAllObjects];

NSSortDescriptor * networkName = [[NSSortDescriptor alloc] initWithKey:@SSID_STRascending:YES] autorelease];
NSArray * descriptors = [NSArray arrayWithObjects:networkName,nil];

[scan_networks addObjectsFromArray:[uniqueNetwork sortedArrayUsingDescriptors:descriptors]];
}

如何解决,谢谢

解决方案

你可以使用NSSET,但是如果只有在命令无关紧要的时候才使用NSSET,那么请问这个方法。回答。在NSmutableArray数组的位置放置你的NSmutableArray包含重复的值。

  NSArray * copy = [NSmutableArray copy]; 

NSInteger index = [copy count] - 1;

([copy reverseObjectEnumerator]中的id对象)
{

if([NSmutableArray indexOfObject:Object inRange:NSMakeRange(0,index)]!= NSNotFound )

{
[NSmutableArray removeObjectAtIndex:index];

}

index--;
}

[复制版];


i'm scanning wifi info using NSMutableArray, but there are few duplicate values appear, so i try to use following code but still getting the duplicate values,

if([scan_networks count] > 0) 
{
    NSArray *uniqueNetwork = [[NSMutableArray alloc] initWithArray:[[NSSet setWithArray:scan_networks] allObjects]];
    [scan_networks removeAllObjects];

    NSSortDescriptor *networkName = [[[NSSortDescriptor alloc] initWithKey:@"SSID_STR" ascending:YES] autorelease];
    NSArray *descriptors = [NSArray arrayWithObjects:networkName,nil];

    [scan_networks addObjectsFromArray:[uniqueNetwork sortedArrayUsingDescriptors:descriptors]];
}

how this can be resolve, thanks

解决方案

You can use NSSET but if you it is only used when order doesn't matter if order matter then go for this approach.I have used it and it give perfect answer. in Place of NSmutableArray array put your NSmutableArray which contains duplicate Value.

NSArray *copy = [NSmutableArray copy];

NSInteger index = [copy count] - 1;

for (id object in [copy reverseObjectEnumerator])
 {

 if ([NSmutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound)

 {
        [NSmutableArray removeObjectAtIndex:index];

 }

    index--;
}

[copy release];

这篇关于如何在NSMutableArray中删除重复的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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