Created
May 29, 2013 10:26
-
-
Save kirang89/5669365 to your computer and use it in GitHub Desktop.
Playing with Array and Dictionary in Objective-C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
//Mutable Array | |
NSMutableArray *array; | |
array = [NSMutableArray arrayWithCapacity:4]; | |
[array addObject: @"one"]; | |
[array addObject: @"two"]; | |
[array addObject: @"three"]; | |
for(NSString *string in array){ | |
NSLog(@"%@", string); | |
} | |
//Dictionary | |
NSDictionary *dict; | |
dict = [NSDictionary dictionaryWithObjectsAndKeys: @"1", @"one", @"2", @"two", nil]; | |
NSLog(@"One: %@", [dict objectForKey: @"one"]); | |
NSLog(@"Two: %@", [dict objectForKey: @"two"]); | |
//Mutable Dictionary | |
NSMutableDictionary *mDict; | |
mDict = [NSMutableDictionary dictionary]; | |
[mDict setObject: @"1" forKey: @"one"]; | |
[mDict setObject: @"2" forKey: @"two"]; | |
NSLog(@"One: %@", [mDict objectForKey: @"one"]); | |
NSLog(@"Two: %@", [mDict objectForKey: @"two"]); | |
/* | |
* Dictionaries can only hold objects and not primitive types. | |
* We can use primitive types as dict values by wrapping them into NSNumber | |
*/ | |
int number = 1; | |
float floatval = 1.234566; | |
char character = 'A'; | |
BOOL boolval = YES; | |
NSNumber *intWrapper; | |
intWrapper = [NSNumber numberWithInt: number]; | |
NSNumber *floatWrapper; | |
floatWrapper = [NSNumber numberWithFloat: floatval]; | |
NSNumber *charWrapper; | |
charWrapper = [NSNumber numberWithChar: character]; //Note: Don't use double quotes to wrap chars | |
NSNumber *boolWrapper; | |
boolWrapper = [NSNumber numberWithBool: boolval]; | |
NSMutableDictionary *varDict; | |
varDict = [NSMutableDictionary dictionary]; | |
[varDict setObject: intWrapper forKey: @"integer"]; | |
[varDict setObject: floatWrapper forKey: @"float"]; | |
[varDict setObject: charWrapper forKey: @"char"]; | |
[varDict setObject: boolWrapper forKey: @"boolean"]; | |
//Store a null value by wrapping it with NSNull | |
[varDict setObject: [NSNull null] forKey: @"null"]; | |
NSLog(@"Integer: %@", [varDict objectForKey: @"integer"]); | |
NSLog(@"Float: %@", [varDict objectForKey: @"float"]); | |
NSLog(@"Char: %c", [[varDict objectForKey: @"char"] charValue]); | |
NSLog(@"Boolean: %@", [varDict objectForKey: @"boolean"]); | |
NSLog(@"NUll value: %@", [varDict objectForKey: @"null"]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment