Objective-C learning note _ dictionary, set, array sorting

Source: Internet
Author: User
Tags allkeys

Objective-C learning note _ dictionary, set, array sorting

One dictionary, two collection, three array dictionary sets, fast traversal, four array sorting, five array elements sorted by numerical values

I. Dictionaries

Dictionary? To save the set of key-value pairs.For "Name: Zhang San", the key is "name", and the value corresponding to the key is "Zhang San ". What is a key-value pair? Entries. The dictionary is the container that stores key-value pairs. Different from arrays,The dictionary depends on the key to access elements. Key cannot be repeated, and value must be an object. Key-value pairs are unordered in the dictionary.Dictionaries can also be divided into NSDictionary and NSMutableDictionary ).

NSDictionary, an unchangeable dictionary, inherits NSObject. That is, once a dictionary is created, the key-value pair cannot be changed, cannot be added, or deleted. Only the key or value can be read.

/* Immutable dictionary * // * Create object */NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys: @ ZhangSan, @ name, @ Man, @ sex, @ 18, @ age, @ 130, @ weight, nil];/* output dictionary */NSLog (@ % @, dic);/* Get all Key values */[dic allKeys]; NSLog (@ % @, [dic allKeys]);/* Get all Value values */[dic allValues]; NSLog (@ % @, [dic allValues]); /* query the Value through the Key */[dic objectForKey: @ name]; NSLog (@ % @, [dic objectForKey: @ name]); [dic valueForKey: @ name]; NSLog (@ % @, [dic valueForKey: @ name]);/* traverse dictionary */NSArray * keyArr = [dic allKeys]; for (int I = 0; I <keyArr. count; I ++) {NSString * keyStr = [keyArr objectAtIndex: I]; NSLog (@%@, [dic objectForKey: keyStr]);} /* fast traversal */for (NSString * key in dic) {NSLog (@ % @, [dic objectForKey: key]);} /* keyArr fast traversal */for (NSString * str in keyArr) {NSLog (@%@, str );}

NSMutableDictionary, a variable dictionary that inherits NSDictionary. Which key-value pairs can be managed? Add, delete, and modify rows.

/* Variable dictionary */NSMutableDictionary * mDic = [NSMutableDictionary dictionaryWithObjectsAndKeys: @ LiSi, @ name, @ 18, @ age, @ woman, @ sex, @ 120, @ weight, nil]; for (NSString * key in mDic) {NSLog (@ % @, [mDic objectForKey: key]);}/* Add a key-Value Pair */[mDic setObject: @ 170 cm forKey: @ height]; [mDic setValue: @ volleyball forKey: @ holobby]; for (NSString * key in mDic) {NSLog (@ % @, [mDic objectForKey: key]);}/* modify the key-Value Pair */[mDic setObject: @ 20 forKey: @ age]; for (NSString * key in mDic) {NSLog (@ % @, [mDic objectForKey: key]);}/* delete key-value pairs */[mDic removeObjectForKey: @ holobby]; for (NSString * key in mDic) {NSLog (@ % @, [mDic objectForKey: key]);}
Ii. Collection class

Collection class* NSSet, similar to the concept of integration in mathematics,It is deterministic, unordered, and heterosexual *. That is, the elements stored in the collection must be of the object type. The stored elements are unordered and the stored elements are unique. Collection classes are also divided into NSSet and NSMutableSet.

The sample code of NSSet is as follows:

/* Unchangeable Set */* Create */NSSet * set = [NSSet setWithObjects: @ Siping, @ Changchun, @ Jilin, @ Siping, nil]; /* obtain the number of Set elements */NSLog (@ % lu, set. count);/* Get an element in the Set */NSLog (, [set anyObject]); /* determine whether the Set contains an object */if ([set containsObject: @ Shenyang]) {NSLog (@ );} else {NSLog (@ );} /* traverse the set */for (NSString * str in set) {NSLog (@%@, str );}

The sample code of NSMutableSet is as follows:

/* Variable set */NSSet * set2 = [NSSet setWithObjects: @ DaLian, @ BeiJing, nil]; NSMutableSet * mSet = [NSMutableSet setWithSet: set2]; /* merge two sets */[mSet unionSet: set]; for (NSString * str in mSet) {NSLog (, str );} /* intersection of two sets */[mSet intersectSet: set];/* add element */[mSet addObject: @ Tonghua];/* Delete element */[mSet removeObject: @ BeiJing]; for (NSString * str in mSet) {NSLog (@ * % @ *, str );}

NSCountedSet is a subclass of NSMutableSet, which records the number of repeat of elements. Added the count function based on NSSet.

The sample code of NSCountedSet is as follows:

/* NSCountedSet class */NSArray * arr = [NSArray arrayWithObjects: @ Zhang, @ LiSi, @ LiSi, @ Wang, @ Wang, @ LiSi, nil]; NSCountedSet * countSet = [NSCountedSet setWithArray: arr];/* view the number of countSet elements */NSLog (@ % lu, countSet. count);/* LiSi count */NSLog (@ % lu, [countSet countForObject: @ LiSi]);
3. Fast traversal of arrays, dictionaries, and collections
for (<#type *object#> in <#collection#>) {}
An object is an element object obtained through traversal. Collection is a collection type object: array, Dictionary, set.

Enumeration features of set types

Array EnumerationObtain Element Object. Dictionary EnumerationObtain Key Value. Set EnumerationObtain Element Object.
NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys: @ ZhangSan, @ name, @ Man, @ sex, @ 18, @ age, @ 130, @ weight, nil]; /* fast traversal */for (NSString * key in dic) {NSLog (@ % @, [dic objectForKey: key]);}
Iv. array sorting

Array sorting depends on the judgment condition, and the judgment condition determines the sorting? Type (ascending or descending ). Does iOS provide sorting for arrays? And provides an interface for us to pass judgment conditions.

NSMutableArray * mArr = [NSMutableArray arrayWithObjects: @ 3, @ 2, @ 1, @ 4, nil];/* variable array sorting * // * @ selector --> method selector, obtain the meaning of a method name. * compare: --> method of the element in the array (the element is a string and compare is a string) */[mArr sortUsingSelector: @ selector (compare :)]; NSLog (@ % @, mArr);/* unchangeable array sorting */NSArray * arr = [NSArray arrayWithObjects: @ 4, @ 2, @ 1, @ 3, nil]; NSArray * sortArr = [arr sortedArrayUsingSelector: @ selector (compare :)]; NSLog (@%@, sortArr );
5. array elements are sorted by numerical values

The elements stored in the array are of the object type. If all the stored elements are numerical objects, sorting by the above method will not produce correct results. Therefore, you must use NSNumberFormatter to convert a string to an NSNumber object. The specific implementation code is as follows:

# Sort The pragma mark-value array # if 1 NSArray * arr = @ [@ 1, @ 12, @ 122, @ 67, @ 50, @ 666]; NSMutableArray * numArr = [NSMutableArray array]; for (NSString * string in arr) {// NSNumberFormatter format conversion NSNumberFormatter * format = [[NSNumberFormatter alloc] init]; // NSString to NSNumber * num = [format numberFromString: string]; [numArr addObject: num];} // call the corresponding method based on the element type in the array, it is equivalent to determining NSLog (@ % @, [numArr sortedArrayUsingSelector: @ selector (compare :)]) in the sorting condition; # endif

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.