Object-C,NSSet,不可變集合

小雷FansUnion發表於2015-12-03

  又到晚上了,繼續碼程式碼。

  正在此時,老爸一個電話”海闊憑魚躍,天高任鳥飛“,老爸不在為老問題煩我了。

   自由了,突然感覺壓力好大啊。

  將來混的太慘,可咋辦啊~


  第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,是沒啥問題的。

相關文章