Skip to content

Latest commit

 

History

History
101 lines (70 loc) · 3.1 KB

2015_07_14.md

File metadata and controls

101 lines (70 loc) · 3.1 KB

Objective

####Code Sample

NSDictionary / NSMutableDictionary

The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values... A key-value pair within a dictionary is called an entry. Each entry consists of one object that represents the key and a second object that is that key’s value. Within a dictionary, the keys are unique. That is, no two keys in a single dictionary are equal.

http://rypress.com/tutorials/objective-c/data-types/nsdictionary

Exercises

Create an NSDictionary containing your name (NSString*), your age (NSString*), and your height (NSString*)

NSDictionary *mike = [[NSDictionary alloc] initWithObjectsAndKeys:@"mike", @"name", @26, @"age", @68, @"height", nil];

or

NSArray *objects = [NSArray arrayWithObjects:@"mike", @26, @68, nil];
NSArray *keys = [NSArray arrayWithObjects:@"name", @"age", @"height", nil];
NSDictionary *mike = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];

or

NSDictionary *mike = @{
  @"name"   : @"mike",
  @"age"    : @26,
  @"height" : @68
};

Print the NSDictionary

NSLog(@"%@", mike);
/*
2015-07-14 13:10:40.643 Dictionaries[30728:4723092] {
    age = 26;
    height = 68;
    name = mike;
}
*/

Print the object for the key "name"

NSString *name = [mike objectForKey:@"name"];
NSLog(@"%@", name);

Print the object for the key "age" Recreate the above dictionary as an NSMutableDictionary Add an entry for "favorite_color" Add an entry for "celebrity_crush"

Cities/States

The following exercise was originally written in Python, taken from http://learnpythonthehardway.org/book/ex39.html.

Create an NSMutableDictionary of states (key: state name, value: state abbr)

Create an NSMutableDictionary of cities (key: state abbr, value: city name)

Add two more cities (setObject:ForKey:)

Print out some cities

Print out some states

Print out some cities through the states dictionary

Print every state abbreviation (enumeration)

Print every city in state (enumeration)

Do both at the same time using the common state abbreviation

What happens if you try to access a key that doesn't exist? (@"texas");

Does dict[@"key"] produce different results from [dict valueForKey:@"key"] ?

Bonus

Do the exercises above in Swift

NSSet / NSMutableSet

http://rypress.com/tutorials/objective-c/data-types/nsset

Algorithm

http://www.scifac.ru.ac.za/javabook/ch02.htm

Additional reading:

http://rypress.com/tutorials/objective-c/data-types/nsdictionary
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/index.html