iPhone - 从NSArray对象获取唯一值 [英] iPhone - getting unique values from NSArray object
问题描述
我有一个由自定义类的对象组成的 NSArray
。该类有3个(city,state,zip)字符串属性。我想从数组中获取所有唯一的状态值
。
I have an NSArray
formed with objects of a custom class. The class has 3 (city, state, zip) string properties. I would like to get all unique state values from the array
.
我读过 NSPredicate
类但在这种情况下无法充分利用它。我能找到的唯一例子是字符串操作。
I did read through the NSPredicate
class but couldn't make much of how to use it in this case. The only examples I could find were for string operations.
有人可以帮帮我吗?
推荐答案
完全简单的一个班轮:
NSSet *uniqueStates = [NSSet setWithArray:[myArrayOfCustomObjects valueForKey:@"state"]];
诀窍是 valueForKey:
方法的NSArray
。这将遍历您的数组( myArrayOfCustomObjects
),在每个对象上调用 -state
方法,并构建一个数组结果。然后我们使用生成的状态数组创建一个 NSSet
来删除重复项。
The trick is the valueForKey:
method of NSArray
. That will iterate through your array (myArrayOfCustomObjects
), call the -state
method on each object, and build an array of the results. We then create an NSSet
with the resulting array of states to remove duplicates.
从iOS 5和OS X 10.7开始,还有一个新类可以执行此操作: NSOrderedSet
。有序集的优点是它将删除任何重复项,但也保持相对顺序。
Starting with iOS 5 and OS X 10.7, there's a new class that can do this as well: NSOrderedSet
. The advantage of an ordered set is that it will remove any duplicates, but also maintain relative order.
NSArray *states = [myArrayOfCustomObjects valueForKey:@"state"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:states];
NSSet *uniqueStates = [orderedSet set];
这篇关于iPhone - 从NSArray对象获取唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!