又到晚上了,继续码代码。
正在此时,老爸一个电话”海阔凭鱼跃,天高任鸟飞“,老爸不在为老问题烦我了。
自由了,突然感觉压力好大啊。
将来混的太惨,可咋办啊~
第1个例子是,不可变集合。
Set集合,概念是通用的,无非是和Java中的java.util.Set语法不一致,方法的个数不一致罢了。
集合的核心特征,就是元素不会重复,是否重复根据元素的hashCode和equals方法来定。
代码
// // main.m // NSSetTest // // Created by fansunion on 15/12/3. // Copyright (c) 2015年 demo. All rights reserved. // #import <Foundation/Foundation.h> //定义一个函数,可以把Array或者NSSet集合转换为字符串 NSString* NSCollectionToString(id collection){ NSMutableString* str = [NSMutableString stringWithString:@"["]; //使用for-each循环语法,遍历集合 for(id obj in collection){ [str appendString:[obj description]]; [str appendString:@", "]; } //获取字符串长度,去掉最后2个多余的字符 NSUInteger length = [str length]; [str deleteCharactersInRange:NSMakeRange(length-2, 2)]; [str appendString:@"]"]; return str; } //NSSet是不可变集合,可变集合是NSMutableSet。 //与NSArray,NSMutableArray一个鸟样 int main(int argc, const char * argv[]) { @autoreleasepool { //构造4个元素的集合,其中2个是重复的 NSSet* set1 = [NSSet setWithObjects:@"A", @"B",@"C",@"B",nil]; NSLog(@"The set1 count :%ld",[set1 count]); NSLog(@"The set1 :%@",NSCollectionToString(set1)); //set1是不可变集合 NSSet* set2 =[set1 setByAddingObject:@"D"]; NSLog(@"The new set1 :%@",NSCollectionToString(set1)); NSLog(@"The set2 :%@",NSCollectionToString(set1)); BOOL isSubSet =[set1 isSubsetOfSet:set2]; NSLog(@"The set1 is subSet of set2:%d",isSubSet); BOOL have = [set1 containsObject:@"C"]; NSLog(@"The set1 has C:%d",have); } return 0; }
运行结果
2015-12-03 20:16:52.049 NSSetTest[5903:419290] The set1 count :3
2015-12-03 20:16:52.050 NSSetTest[5903:419290] The set1 :[A, B, C]
2015-12-03 20:16:52.050 NSSetTest[5903:419290] The new set1 :[A, B, C]
2015-12-03 20:16:52.051 NSSetTest[5903:419290] The set2 :[A, B, C]
2015-12-03 20:16:52.051 NSSetTest[5903:419290] The set1 is subSet of set2:1
2015-12-03 20:16:52.051 NSSetTest[5903:419290] The set1 has C:1
Program ended with exit code: 0
照目前这个学习进度,2017年之前,初步掌握Object-C和iOS,是没啥问题的。