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)