The de-weight of IOS arrays (normal unordered de-weight and sorted good go-heavy)

Source: Internet
Author: User
Tags allkeys

This article reprinted to http://blog.csdn.net/zhaopenghhhhhh/article/details/24972645

Sometimes it is necessary to remove duplicate elements from the Nsarray, and the presence of elements in the nsarray is not necessarily the nsstring type. Today I think about it, add friends help, think of two solutions, first divided into the following.

1. Using the Nsdictionary AllKeys (allvalues) method

You can save the elements in the Nsarray in a dictionary, and then use AllKeys or allvalues to get all the keys or values of the dictionary, which are de-weighed.

Example code:

nsarray *arr = @[@111,@222,@111];

nsmutabledictionary *dict = [nsmutabledictionary dictionary];

for (nsnumber *number in arr) {

[Dict setobject: Number Forkey: number];

}

NSLog(@ "%@", [dict allvalues]);

The output is:

2013-05-21 12:03:49.449 Test1[4377:c07] (

111,

222

)

2. Using the AllObjects method of Nsset

This method is faster, and using Nsset does not add the attributes of the repeating element. But the go-to-heavy array is not sorted, and if you need to sort, you can use the Nssortdescriptor class.

Example code:

nsarray *arr = @[@111,@222,@111];

nsset *set = [nsset setwitharray: arr];

NSLog(@ "%@", [set allobjects]);

The output is:

2013-05-21 12:06:26.508 Test1[4547:c07] (

111,

222

)

Sort of the de-weight

Many times you may encounter elements that need to be removed from Nsarray, using a number of methods.

The most convenient and fast is the nsset. But nsset, sometimes the order of the array elements

Upset. Then another method is as follows:

nsmutablearray *categoryarray = [[nsmutablearray alloc] init];

for (unsigned i = 0; i < [NameArray Count]; i++) {

if ([Categoryarray containsobject: [NameArray objectatindex: i]] = = NO) {

[Categoryarray addobject: [NameArray objectatindex: i]];

}

}

The order will not be chaotic.

The de-weight of IOS arrays (normal unordered and sorted redo)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.