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)
從字串分割到陣列- componentsseparatedbystr
ing:
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中不能存在重複的物件
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
ios學習筆記之Object C 字串
在object c中,字串的宣告是 nsstring astring astring並不真正包含乙個字串物件 它是指向記憶體中字串物件的指標。和c語言中,用指標指向字串的宣告類似 nsstring a0 nsstring alloc initwithformat kevin 方法一 nsstring...
iOS開發 Object C學習之結構體使用
前言 定義 結構體並不是定義乙個變數,而是定義了種資料型別。結構體作用 結構體和其他型別基礎資料型別一樣,例如int型別,char型別 只不過結構體可以做成你想要的資料型別。以方便日後的使用。在實際專案中,結構體是大量存在的。研發人員常使用結構體來封裝一些屬性來組成新的型別。由於c語言內部程式比較簡...
iOS開發 Object C學習之結構體使用
前言 定義結構體並不是定義乙個變數,而是定義了種資料型別。結構體作用 結構體和其他型別基礎資料型別一樣,例如int型別,char型別 只不過結構體可以做成你想要的資料型別。以方便日後的使用。在實際專案中,結構體是大量存在的。研發人員常使用結構體來封裝一些屬性來組成新的型別。由於c語言內部程式比較簡單...