ios學習筆記之Object-C—集合

Obejct-C中包含了三種集合,分別是:數組、字典和集(set)。

    數組和C語言中的數組相似,但是OC中的數組只能存儲對象,不能存儲基本數據類型,如int、float、enum、struct等,也不能存儲nil。它也提供了編制好的索引對象,可以通過制定索引找到要查看的對象。包含可變數組(NSMutableArray)和不可變數組(NSArray)。
    字典存放的是“鍵值對”,即key-value,可以通過鍵值查找到字典中保存的對象。
    集保存的也是對象,集和字典中保存的對象都是無序的,但是字典可以通過key進行虛擬排序。
    集和字典中不能存在相同的對象,如果對象一致,且是開始定義時寫入的,則後面的對象無法寫入,如果是後來添加的,則會把原來相同的對象頂替。

    基本用法:
  •     數組
    初始化不可變數組:    
NSArray *array = [[NSArray alloc] initWithObjects:@"one",@"Two",@"Three",nil];此數組只有三個對象,one,two,three,最後的nil可以看出結束符,並不會存入數組中。
    NSLog(@"array count = %d",[array count]);  //打印數組中對象個數
    [array objectAtIndex:2]    //或許索引2處的對象
    初始化可變數組:
NSMutableArray *Mutablearray = [NSMutableArray arrayWithCapacity:0];    //設置可變數組初始長度爲0;

    從一個數組拷貝到另一個數組
    Mutablearray = [NSMutableArray arrayWithArray:array];   //將array的對象拷貝到Mutablearray中

    在可變數組末尾添加對象
    [Mutablearray addObject:@"Four"];

    快速枚舉:
    OC中提供了快速又集中的訪問遍歷數組、字典、集的方法,稱爲快速枚舉
如,現在array數組中存在的是字符串的對象,所以快速枚舉如下:
for(NSString *str in array)
{
      NSLog(@"array = %@",str);    //可以一一輸出數組array中的對象
}
    
    從字符串分割到數組- componentsSeparatedByString:
    NSString *string = NSString alloc] initWithString:@"One,Two,Three,Four"];

    NSLog(@"string:%@",string);    

    NSArray *array = [string componentsSeparatedByString:@","];

    NSLog(@"array:%@",array);

    [string release];


    //從數組合並元素到字符串- componentsJoinedByString:

    NSArray *array = NSArray alloc] initWithObjects:@"One",@"Two",@"Three",@"Four",nil];

    NSString *string = [array componentsJoinedByString:@","];

    NSLog(@"string:%@",string);

    刪除可變數組指定索引處的對象:

    [Mutablearray removeObjectAtIndex:1];    

    

  •     創建字典
    NSDictionary *dictionary = NSDictionary alloc] initWithObjectsAndKeys:@"One",@"1",@"Two",@"2",@"Three",@"3",nil];

    NSString *string = [dictionary objectForKey:@"One"];

    NSLog(@"string:%@",string);

    NSLog(@"dictionary:%@",dictionary);

    [dictionary release];


    創建可變字典:

    //創建

    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];


    //添加字典

    [dictionary setObject:@"One" forKey:@"1"];

    [dictionary setObject:@"Two" forKey:@"2"];

    [dictionary setObject:@"Three" forKey:@"3"];

    [dictionary setObject:@"Four" forKey:@"4"];

    NSLog(@"dictionary:%@",dictionary);


    //刪除指定的字典

    [dictionary removeObjectForKey:@"3"];

    NSLog(@"dictionary:%@",dictionary);


 

  •     集合NSSet

    //NSSet中不能存在重複的對象

    NSMutableSet *set1 = [[NSMutableSet alloc] initWithObjects:@"1",@"2",@"3", nil]; 

   NSMutableSet *set2 = [[NSMutableSet alloc] initWithObjects:@"1",@"5",@"6", nil]; 


    [set1 unionSet:set2];   //取並集1,2,3,5,6

    [set1 intersectSet:set2];  //取交集1

 

    [set1 minusSet:set2];    //取差集2,3,5,6

發佈了8 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章