NSArray 和 NSSet
//快速定义数组 NSArray *arrays =@[@"dajie",@"xiaojie",@"jinyu"]; // 快速遍历 for (id obj in arrays) { NSUInteger i = [arrays indexOfObject:obj]; NSLog(@"%ld - %@",i,obj); } //另一种遍历 [arrays enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"%ld,%@",idx,obj); }]; //字符串数组的遍历 NSString *strs =@"dajie-xiaojie-jinyu-feng"; NSArray *array = [strs componentsSeparatedByString:@"-"]; for(NSString *line in array) { NSUInteger p = [array indexOfObject:line]; NSLog(@"%ld - %@",p,line); } //可变数组 NSMutableArray *muArray = [NSMutableArray arrayWithObjects:@"dajie",@"xiaojie",@"jinyu", nil]; //添加元素 [muArray addObject:@"huagou"]; //删除元素 [muArray removeObject:@"huagou"]; // [muArray removeAllObjects];//删除所有元素 [muArray removeObjectAtIndex:2]; NSLog(@"%ld",muArray.count); for (id obj in muArray) { NSLog(@"%@",obj); }
可变数组
1 NSMutableArray *array = [NSMutableArray array]; 2 [array addObject:@"dajie"]; 3 [array addObject:@"Hello"]; 4 // [array addObject:nil];// 不能放nil 5 [array removeObject:@"Hello"]; 6 NSLog(@" %ld - %@",array.count,array);
NSSet
1 // set 基本使用 2 NSSet *s1 = [NSSet set];//初始化 3 NSSet *s3 = [NSSet setWithObject:@"ok"]; 4 NSSet *s2 = [NSSet setWithObjects:@"jinyu",@"dajie",@"age" ,nil]; 5 [s1 anyObject]; 6 NSString *str = [s2 anyObject];//取出随机元素 7 NSLog(@"%@ %@%ld %@",s3,s2,s2.count,str); 8 9 NSMutableSet *s = [NSMutableSet set]; 10 [s addObject:@"ok"]; 11 [s removeObject:@"ok"]; 12 [s removeAllObjects];
NSArray 与 NSSet区别
1 // NSSet 和 NSArray比较 2 // 共同点,都是集合,都只能存储oc对象 不能存储非OC对象如:(基本数据类型 int 、double 、floa、t char、 结构体、枚举、共用体) 3 // 本身都不可变,都有一个可变的子类 4 // 不同点 NSarray 有序 NSSet无序