NSArray和NSSet都是用于存储对象的集合;NSSet、NSMutableSet声明的对象,是无序的集合,在内存中存储方式是不连续的;而NSArray、NSMutableArray声明的对象,是有序集合,在内存中的存储位置也是连续的。
NSSet
NSSet *set = [NSSet setWithObjects:@"1", @"2", @"3", @"4", @"5", @"6",@"7",@"8", nil];
NSLog(@"set:%@", set);
打印结果:
set:{(7, 3,8,4,5,1,6, 2)}
NSMutableSet
NSMutableSet *mutableSet = [NSMutableSet setWithObjects:@"1", @"2", @"3", @"4", @"5", @"6",@"7",@"8", nil];
[mutableSet addObject:@"9"];
NSLog(@"mutableSet:%@", mutableSet);
打印结果:
mutableSet:{(7,3,8,4,9,5,1,6,2)}
NSArray
NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6",@"7",@"8", nil];
NSLog(@"array:%@", array);
打印结果:
array:(1,2,3,4,5,6,7,8)
NSMutableArray
NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6",@"7",@"8", nil];
[mutableArray addObject:@"9"];
NSLog(@"mutableArray:%@", mutableArray);
打印结果:
mutableArray:(1,2,3,4,5,6,7,8,9)
NSSet和NSArray的区别,在搜索一个单元素时NSSet比NSArray的效率高,主要是因为NSSet用到了哈希算法(hash)
同时NSSet中是数据无重复集合,而NSArray中数据是可以重复的
NSSet
NSSet *set = [NSSet setWithObjects:@"1", @"2", @"3", @"4", @"5", @"6",@"7",@"8",@"1",@"2", @"3", @"4", nil];
NSLog(@"set:%@", set);
打印结果:
set:{(2,3,4,5,6,7,8,1)}
NSArray
NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6",@"7",@"8",@"1", @"2", @"3", @"4", nil];
NSLog(@"array:%@", array);
打印结果:
array:(1,2,3,4,5,6,7,8,1,2,3,4)