In this tutorial, we will be covering various functions available in NSDictionary. NSDictionary help us in creating static dictionary.

Modern Objective C Dictionary notations.

There is modern Objective C syntax that makes it easier for us to create and retrieve objects. Xcode actually changes to required format in build time. The syntax for initialization and accessing is as shown below.

	// initialization
	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    // access value for key1
    NSString *value = dict[@"key1"];
    NSLog(@"%@",value);

Creating a Dictionary

+ dictionary

Creates and returns an empty dictionary.

Example

			// initialization
			NSDictionary *dict = [NSDictionary dictionary];
        	NSLog(@"%@",dict);
		

Output

2014-03-22 06:10:21.734 iOSTutorial[493:303] {
}		

+ dictionaryWithContentsOfFile:

Creates and returns a dictionary using the keys and values found in a file specified by a given path. This method allows us to read an dictionary from a apple propery list(plist) file. Assuming we have the following data in plist named sample-dictionary-plist that is added to our project.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>key1</key>
	<string>Eezy</string>
	<key>key2</key>
	<string>Tutorials</string>
</dict>
</plist>

Example

NSString *file = [[NSBundle mainBundle] pathForResource:@"sample-dictionary-plist" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:file];

Output

2014-03-22 07:12:31.268 iOS-Tutorial[767:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}		

+ dictionaryWithContentsOfURL:

Creates and returns a dictionary using the keys and values found in a resource specified by a given URL.

Example

	NSURL *url = [NSURL URLWithString:@"http://ios.eezytutorials.com/sample-files/sample-dictionary-plist.plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfURL:url];
    NSLog(@"%@",dict);		
	

Output

2014-03-22 07:12:31.268 iOS-Tutorial[767:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}			
		

+ dictionaryWithDictionary:

Creates and returns a dictionary containing the keys and values from another given dictionary.

Example

	NSDictionary *tempDictionary = @{@"key1":@"Eezy",@"key2": @"Tutorials"};

	NSDictionary *dict =  [NSDictionary dictionaryWithDictionary:tempDictionary];	
	
	NSLog(@"%@",dict);
		

Output

2014-03-22 07:12:31.268 iOS-Tutorial[767:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}	
		

+ dictionaryWithObject:forKey:

Creates and returns a dictionary containing a given key and value.

Example

	NSDictionary *dict =  [NSDictionary dictionaryWithObject:@"Eezy" forKey:@"key1"];	
	
	NSLog(@"%@",dict);		
		

Output

2014-03-22 07:12:31.268 iOS-Tutorial[767:a0b] {
    key1 = Eezy;
}			
		

+ dictionaryWithObjects:forKeys:

Creates and returns a dictionary containing entries constructed from the contents of an array of keys and an array of values.

Example

	NSDictionary *dict =  [NSDictionary dictionaryWithObjects:@[@"Eezy",@"Tutorials"]
	forKeys:@[@"key1",@"key2"]];	
	
	NSLog(@"%@",dict);			
		

Output

2014-03-22 07:12:31.268 iOS-Tutorial[767:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}			
		

+ dictionaryWithObjects:forKeys:count:

Creates and returns a dictionary containing count objects from the objects array.

Example

	NSString *values[3];
    values[0] = @"Eezy";
    values[1] = @"Tutorials";
    values[2] = @"Website";
    
    NSString *keys[3];
    keys[0] = @"key1";
    keys[1] = @"key2";
    keys[2] = @"key3";
	NSDictionary *dict =  [NSDictionary dictionaryWithObjects:values forKeys:keys count:2];	
	
	NSLog(@"%@",dict);
		

Output

2014-03-22 12:32:05.909 iOS-Tutorial[661:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}
		

+ dictionaryWithObjectsAndKeys:

Creates and returns a dictionary containing entries constructed from the specified set of values and keys.

Example

	NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
	@"Eezy",@"key1",@"Tutorials",@"key2", nil];

    NSLog(@"%@",dict);
		

Output

2014-03-22 12:22:30.561 iOS-Tutorial[632:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}		

Initializing an NSDictionary Instance

- init

Initializes a newly allocated dictionary. Recommended use is [NSDictionary dictionary] instead of [[NSDictionary alloc]init]

Example

	NSDictionary *dict = [[NSDictionary alloc]init];
    NSLog(@"%@",dict);
		

Output

2014-03-22 12:43:21.163 iOS-Tutorial[735:a0b] {
}
		

- initWithContentsOfFile:

Initializes a newly allocated dictionary using the keys and values found in a file at a given path. This method allows us to read an dictionary from a apple propery list(plist) file. Assuming we have the following data in plist named sample-dictionary-plist that is added to our project.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>key1</key>
	<string>Eezy</string>
	<key>key2</key>
	<string>Tutorials</string>
</dict>
</plist>

Example

	NSString *file = [[NSBundle mainBundle] pathForResource:@"sample-dictionary-plist" ofType:@"plist"];
	NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:file];
		

Output

2014-03-22 12:46:54.516 iOS-Tutorial[768:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}
		

- initWithContentsOfURL:

Initializes a newly allocated dictionary using the keys and values found at a given URL.

Example

	NSURL *url = [NSURL URLWithString:@"http://ios.eezytutorials.com/sample-files/sample-dictionary-plist.plist"];
    NSDictionary *dict = [[NSDictionary alloc]initWithContentsOfURL:url];
    NSLog(@"%@",dict);		
		

Output

2014-03-22 12:49:01.749 iOS-Tutorial[796:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}
		

- initWithDictionary:

Initializes a newly allocated dictionary by placing in it the keys and values contained in another given dictionary.

Example

	NSDictionary *tempDictionary = @{@"key1":@"Eezy",@"key2": @"Tutorials"};

	NSDictionary *dict =  [[NSDictionary alloc] initWithDictionary:tempDictionary];	
	
	NSLog(@"%@",dict);
		

Output

2014-03-22 12:51:01.806 iOS-Tutorial[808:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}
		

- initWithDictionary:copyItems:

Initializes a newly allocated dictionary using the objects contained in another given dictionary.

Example

	NSDictionary *tempDictionary = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    
	NSDictionary *dict =  [[NSDictionary alloc] initWithDictionary:tempDictionary copyItems:YES];
	
	NSLog(@"%@",dict);
		

Output

2014-03-22 12:51:01.806 iOS-Tutorial[808:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}
		

- initWithObjects:forKeys:

Initializes a newly allocated dictionary with entries constructed from the contents of the objects and keys arrays.

Example

	NSDictionary *dict = [[NSDictionary alloc]
     initWithObjects:@[@"Eezy",@"Tutorials"] forKeys:@[@"key1",@"key2"]];
	NSLog(@"%@",dict);
		

Output

2014-03-22 12:59:08.596 iOS-Tutorial[831:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}		

- initWithObjects:forKeys:count:

Initializes a newly allocated dictionary with count entries.

Example

    NSString *values[3];
    values[0] = @"Eezy";
    values[1] = @"Tutorials";
    values[2] = @"Website";
    
    NSString *keys[3];
    keys[0] = @"key1";
    keys[1] = @"key2";
    keys[2] = @"key3";
    NSDictionary *dict = [[NSDictionary alloc] initWithObjects:values forKeys:keys count:2];
    NSLog(@"%@",dict);
		

Output

2014-03-22 13:01:57.150 iOS-Tutorial[856:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}
		

- initWithObjectsAndKeys:

Initializes a newly allocated dictionary with entries constructed from the specified set of values and keys.

Example

	NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"Eezy",@"key1",@"Tutorials",@"key2", nil];
	NSLog(@"%@",dict);
		

Output

2014-03-22 12:59:08.596 iOS-Tutorial[831:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}		
		

Creating Key Sets for Shared-Key Optimized Dictionaries

+ sharedKeySetForKeys:

Creates a shared key set object for the specified keys. This provides an way for creating optimised dictionary

Example

	id sharedKeySet = [NSDictionary sharedKeySetForKeys:@[@"key1", @"key2"]]; // returns NSSharedKeySet
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithSharedKeySet:sharedKeySet];
    dict[@"key1"] = @"Eezy";
    dict[@"key2"] = @"Tutorials";
    //We can an object thats not in the shared keyset
    dict[@"key3"] = @"Website";
    NSLog(@"%@",dict);		
		

Output

2014-03-22 13:19:09.686 iOS-Tutorial[929:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
    key3 = Website;
}
		

Counting Entries

- count

Returns the number of entries in the dictionary.

Example

	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    NSInteger count = [dict count];
    NSLog(@"%@\nCount = %d",dict,count);		
		

Output

2014-03-22 13:25:01.860 iOS-Tutorial[989:a0b] {
    key1 = Eezy;
    key2 = Tutorials;
}
Count = 2
		

Comparing Dictionaries

- isEqualToDictionary:

Returns a Boolean value that indicates whether the contents of the receiving dictionary are equal to the contents of another given dictionary.

Example

	NSDictionary *dict1 = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
	NSDictionary *dict2 = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    BOOL isEqual = [dict1 isEqualToDictionary:dict2];
    NSLog(@"isEqual = %d",isEqual);		
		

Output

2014-03-22 13:29:55.240 iOS-Tutorial[1032:a0b] isEqual = 1
		

Accessing Keys and Values

- allKeys

Returns a new array containing the dictionary’s keys.

Example

	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    NSArray *allKeys = [dict allKeys];
    NSLog(@"%@", allKeys);		
		

Output

2014-03-22 13:31:40.286 iOS-Tutorial[1048:a0b] (
    key2,
    key1
)
		

- allKeysForObject:

Returns a new array containing the keys corresponding to all occurrences of a given object in the dictionary.

Example

	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials",@"key3":@"Eezy"};
    NSArray *allKeys = [dict allKeysForObject:@"Eezy"];
    NSLog(@"%@", allKeys);		
		

Output

2014-03-22 13:32:50.155 iOS-Tutorial[1063:a0b] (
    key1,
    key3
)
		

- allValues

Returns a new array containing the dictionary’s values.

Example

	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    NSArray *allValues = [dict allValues];
    NSLog(@"%@", allValues);		
		

Output

2014-03-22 13:33:49.490 iOS-Tutorial[1076:a0b] (
    Tutorials,
    Eezy
)
		

- getObjects:andKeys:

Returns by reference C arrays of the keys and values in the dictionary.

Example

 	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    NSInteger count = [dict count];
    __unsafe_unretained id objects[count];
    __unsafe_unretained id keys[count];
    [dict getObjects:objects andKeys:keys];
    
    for (int i = 0; i < count; i++) {
        NSLog(@"%@ : %@",keys[i], objects[i]);
    }		
		

Output

2014-03-22 13:45:47.000 iOS-Tutorial[1129:a0b] key2 : Tutorials
2014-03-22 13:45:47.001 iOS-Tutorial[1129:a0b] key1 : Eezy
		

- objectForKey:

Returns the value associated with a given key.

Example

	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    id obj = [dict objectForKey:@"key1"];
    NSLog(@"%@",obj);		
		

Output

2014-03-22 13:47:18.302 iOS-Tutorial[1146:a0b] Eezy
		

- objectForKeyedSubscript:

Returns the value associated with a given key.

Example

	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    id obj = [dict objectForKeyedSubscript:@"key1"];
    NSLog(@"%@",obj);		
		

Output

2014-03-22 13:55:12.496 iOS-Tutorial[1193:a0b] Eezy
		

- valueForKey:

Returns the value associated with a given key.

Example

	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    id obj = [dict valueForKey:@"key1"];
    NSLog(@"%@",obj);		
		

Output

2014-03-22 13:59:13.834 iOS-Tutorial[1208:a0b] Eezy
		

Enumerating Dictionaries

- keyEnumerator

Returns an enumerator object that lets you access each key in the dictionary.

Example

	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    NSEnumerator *enumerator = [dict keyEnumerator];
    id key;
    while (key =[ enumerator nextObject]) {
        NSLog(@"%@",[dict objectForKey:key]);
    }		
		

Output

2014-03-22 14:04:57.514 iOS-Tutorial[1250:a0b] Tutorials
2014-03-22 14:04:57.516 iOS-Tutorial[1250:a0b] Eezy
		

- objectEnumerator

Returns an enumerator object that lets you access each value in the dictionary.

Example

	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    NSEnumerator *enumerator = [dict objectEnumerator];
    id obj;
    while (obj =[ enumerator nextObject]) {
        NSLog(@"%@",obj);
    }
		

Output

2014-03-22 14:05:55.536 iOS-Tutorial[1262:a0b] Tutorials
2014-03-22 14:05:55.537 iOS-Tutorial[1262:a0b] Eezy
		

- enumerateKeysAndObjectsUsingBlock:

Applies a given block object to the entries of the dictionary.

Example

	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@: %@",key,obj);
    }];		
		

Output

2014-03-22 14:07:28.232 iOS-Tutorial[1275:a0b] key2: Tutorials
2014-03-22 14:07:28.233 iOS-Tutorial[1275:a0b] key1: Eezy
		

- enumerateKeysAndObjectsWithOptions:usingBlock:

Applies a given block object to the entries of the dictionary.

Example

	NSDictionary *dict = @{@"key1":@"Eezy",@"key2": @"Tutorials"};
    [dict enumerateKeysAndObjectsWithOptions:NSEnumerationReverse usingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@: %@",key,obj);
    }];		
		

Output

2014-03-22 14:09:06.224 iOS-Tutorial[1292:a0b] key2: Tutorials
2014-03-22 14:09:06.225 iOS-Tutorial[1292:a0b] key1: Eezy
		

Sorting Dictionaries

- keysSortedByValueUsingSelector:

Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values.

Example

	NSDictionary *dict = @{@"key2":@"Eezy",@"key1": @"Tutorials", @"key3":@"Website"};
    NSArray *keys =  [dict keysSortedByValueUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    NSLog(@"%@",keys);
		

Output

2014-03-22 14:22:00.199 iOS-Tutorial[1377:a0b] (
    key2,
    key1,
    key3
)
		

- keysSortedByValueUsingComparator:

Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using a given comparator block.

Example

	NSDictionary *dict = @{@"key2":@"Eezy",@"key1": @"Tutorials", @"key3":@"Website"};
    NSArray *keys =  [dict keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 isEqualToString:obj2];
    }];
    NSLog(@"%@",keys);	
		

Output

2014-03-22 14:18:10.420 iOS-Tutorial[1363:a0b] (
    key2,
    key1,
    key3
)
		

- keysSortedByValueWithOptions:usingComparator:

Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using a given comparator block and a specified set of options.

Example

	NSDictionary *dict = @{@"key2":@"Eezy",@"key1": @"Tutorials", @"key3":@"Website"};
    NSArray *keys =  [dict keysSortedByValueWithOptions:
		NSSortStable usingComparator:^NSComparisonResult(id obj1, id obj2) {
        	return [obj1 isEqualToString:obj2];
    	}];
                      
    NSLog(@"%@",keys);
		

Output

2014-03-22 14:23:47.303 iOS-Tutorial[1394:a0b] (
    key2,
    key1,
    key3
		

Filtering Dictionaries

- keysOfEntriesPassingTest:

Returns the set of keys whose corresponding value satisfies a constraint described by a block object.

Example

	NSDictionary *dict = @{@"key2":@"Eezy",@"key1": @"Tutorials", @"key3":@"Website"};
    NSSet *resultSet = [dict keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {
        if (![key isEqualToString:@"key3"]) {
            return YES;
        }
        else{
            return NO;
        }
    }];
    NSLog(@"%@",resultSet);		

Output

2014-03-22 14:33:59.211 iOS-Tutorial[1469:a0b] {(
    key2,
    key1
)}
		

- keysOfEntriesWithOptions:passingTest:

Returns the set of keys whose corresponding value satisfies a constraint described by a block object.

Example

 NSDictionary *dict = @{@"key2":@"Eezy",@"key1": @"Tutorials", @"key3":@"Website"};
    NSSet *resultSet = [dict keysOfEntriesWithOptions:NSEnumerationReverse passingTest:^BOOL(id key, id obj, BOOL *stop) {
        if (![key isEqualToString:@"key3"]) {
            return YES;
        }
        else{
            return NO;
        }
    }];
    NSLog(@"%@",resultSet);
		

Output

2014-03-22 14:35:39.861 iOS-Tutorial[1485:a0b] {(
    key2,
    key1
)}
		

Storing Dictionaries

- writeToFile:atomically:

Writes a property list representation of the contents of the dictionary to a given path.

Example

	NSDictionary *dict = @{@"key2":@"Eezy",@"key1": @"Tutorials", @"key3":@"Website"};
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString *documentsDirectory = [pathArray objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myDict.plist"];
    BOOL status = [dict writeToFile:filePath atomically:YES];
    NSLog(@"Write Status %d",status);		
		

Output

2014-03-22 14:41:31.602 iOS-Tutorial[1556:a0b] Write Status 1
		

- writeToURL:atomically:

Writes a property list representation of the contents of the dictionary to a given URL.

Example

	NSDictionary *dict = @{@"key2":@"Eezy",@"key1": @"Tutorials", @"key3":@"Website"};
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString *documentsDirectory = [pathArray objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myDict.plist"];
    NSURL *url = [NSURL fileURLWithPath:filePath];
    BOOL status = [dict writeToURL:url atomically:YES];
    NSLog(@"Write Status %d",status);
		

Output

2014-03-22 14:49:29.712 iOS-Tutorial[1710:a0b] Write Status 1
		

Advertisements