又到晚上了,繼續碼代碼。
正在此時,老爸一個電話”海闊憑魚躍,天高任鳥飛“,老爸不在為老問題煩我了。
自由了,突然感覺壓力好大啊。
將來混的太慘,可咋辦啊~
第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//定義一個函數,可以把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,是沒啥問題的。