Objective-c的Foundation中常用類5——集合中的NSSet、NSMutableSet

來源:互聯網
上載者:User

在Foundation架構中,提供了一組單值對象的集合,且NSSet執行個體中的元素是無序的,同一個對象只能儲存一個,類似於java中的HashSet。感覺java和OC太像了

1、繼續不可變,NSSet

NSSet的建立類似於數組的建立,其實在Objective-c中NSSet和NSArray就很像,在後面會具體講他們之間的區別

NSSet *set1 = [NSSet setWithObjects:@"one",@"two",@"three" nil];//同樣nil不能少        //通過數組來建立        NSArray *array = [NSArray arrayWithObjects:@"hello",@"world",@"hao", nil];                NSSet *set2 = [NSSet setWithArray:array];        //通過已有集合構建        NSSet *set3 = [NSSet setWithSet:set2];                //集合中對象的個數        NSInteger *objNum = [set3 count];                //以數組的形式返回集合中的所有對象        NSArray *array1 = [set3 allObjects];                //看集合中是否包含某對象        BOOL isContain = [set3 containsObject:@"one"];                //集合set2是否是集合set3的子集合        BOOL isSub = [set2 isSubsetOfSet:set3];                //兩個集合是否相同        BOOL isEqual = [set3 isEqualToSet:set2];                //在原有集合的基礎上新加一個元素建立一個新集合        NSSet *set4 = [set3 setByAddingObject:@"yade"];                //把兩個集合合并成一個新的集合        NSSet *set5 =[set3 setByAddingObjectsFromSet:set2];                //把一個集合一個數組合并成一個新集合        NSSet *set6 = [set5 setByAddingObjectsFromArray:array];

2、可變集合NSMutableSet

繼承自NSSet

//首先還是建立兩個再說        NSMutableSet *mSet1 = [NSMutableSet setWithObjects:@"one",@"two",@"1", nil];        NSMutableSet *mSet2 = [NSMutableSet setWithObjects:@"three",@"four",@"1" nil];        //在mSet1中去除和mSet2中相同的元素,返回的是mSet2        [mSet2 minusSet:mSet1];                //獲得兩個集合的交集,返回的是mSet1        [mSet1 intersectSet:mSet2];                //取並集        [mSet1 unionSet:mSet2];                //將一個一個集合中的內容設定成另一個集合中的內容        [mSet1 setSet:mSet2];                //刪除對象        [mSet1 removeObject:@"one"];        //刪除所有        [mSet1 removeAllObjects];

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.