代码改变世界

IOS开发之NSSet应用

2013-04-17 14:53  三戒1993  阅读(122)  评论(0编辑  收藏  举报
NSSet,NSMutableSet,和NSCountedSet类声明编程接口对象的无序集合(散列存储:在内存中的存储位置不连续)。

而NSArray,NSDictionary类声明编程接口对象的有序集合(有序存储:在内存中的存储位置连续)。


NSSet,NSMutableSet; 与NSArray,NSMutableArray的区别一样,NSSet声明静态对象。当创建NSSet对象时初始化,后期气候的条目不能修改。而NSMutableSet对象则是可以动态添加和删除的,同时根据对象长度自动分配内存。

需要注意的是:NSSet,NSArray里面只能添加cocoa对象,如果需要加入基本数据类型(int,float,BOOL,double等),需要将数据封装成NSNumber类型。


NSSet在实际应用中与NSArray区别不大,但是如果你希望查找NSArray中的某一个元素,则需要遍历整个数组,效率低下。而NSSet在查找某一特定的元素的时候则是根据hash算法直接找到此元素的位置,效率高。

NSSet

- (NSArray *)allObjects;

- (id)anyObject;

- (BOOL)containsObject:(id)anObject;

- (NSString *)description;

- (NSString *)descriptionWithLocale:(id)locale;

- (BOOL)intersectsSet:(NSSet *)otherSet;

- (BOOL)isEqualToSet:(NSSet *)otherSet;

- (BOOL)isSubsetOfSet:(NSSet *)otherSet;

+ (id)set;

+ (id)setWithObject:(id)object;

+ (id)setWithObjects:(const id *)objects count:(NSUInteger)cnt;

+ (id)setWithObjects:(id)firstObj, ... NS_REQUIRES_NIL_TERMINATION;

+ (id)setWithSet:(NSSet *)set;

+ (id)setWithArray:(NSArray *)array;


- (id)initWithObjects:(const id *)objects count:(NSUInteger)cnt;

- (id)initWithObjects:(id)firstObj, ... NS_REQUIRES_NIL_TERMINATION;

- (id)initWithSet:(NSSet *)set;

- (id)initWithSet:(NSSet *)set copyItems:(BOOL)flag;

- (id)initWithArray:(NSArray *)array;


NSMutableSet (NSExtendedMutableSet)

- (void)addObjectsFromArray:(NSArray *)array;

- (void)intersectSet:(NSSet *)otherSet;

- (void)minusSet:(NSSet *)otherSet;

- (void)removeAllObjects;

- (void)unionSet:(NSSet *)otherSet;

- (void)setSet:(NSSet *)otherSet;

+ (id)setWithCapacity:(NSUInteger)numItems;

- (id)initWithCapacity:(NSUInteger)numItems;

NSSet的本质上是链表,从内存方面来讲,链表是不规则分布在内存中以指针相连的. 所以内存的地址是不相连的,要想查找某一元素,就要从链表头开始一次查找.

NSArray 存储在空间上是连续的。
因为空间局部性(缓存的存在),数组迭代效率更高。

可以百度看看 数组 和链表 效率!