數組、字典和集合的基本用法
數組和集合的區別:
NSSet和NSArray都是對象容器,用于存儲對象,屬于集合; NSSet , NSMutableSet是無序的集合,在內存中存儲方式是不連續的,NSArray是有序的集合,在內存中存儲位置是連續的;
NSSet和NSArry區別是:在搜索一個一個元素時NSSet比NSArray效率高,主要是它用到了一個算法hash;開發文檔中這樣解釋:You can use sets as an alternative to arrays when the order of elements isn’t important and performance in testing whether an object is contained in the set is a consideration—while arrays are ordered, testing for membership is slower than with sets.
比如你要存儲元素A,一個hash算法直接就能直接找到A應該存儲的位置;同樣,當你要訪問A時,一個hash過程就能找到A存儲的位置。而對于NSArray,若想知道A到底在不在數組中,則需要便利整個數組,顯然效率較低了;
NSSet,NSArray都是類,只能添加cocoa對象,如果需要加入基本數據類型(int,float,BOOL,double等),需要將數據封裝成NSNumber類型。
另:可變和不可變(數組)
可變數組和不可變數組常用方法?其中有幾個方法比較實用,比如:
5)將數組中的字符串拼接成一個新的字符串,并在每個元素中間添加“-”
NSString *string= [newArray2 componentsJoinedByString:@"-"];
6)將字符串分隔成數組元素
NSArray*array12 = [string2 componentsSeparatedByString:@"="];NSLog(@"%@",array12);