Objective-C Language
NSDictionary
Zoeken…
creëren
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
of
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
of met de juiste letterlijke syntaxis
NSDictionary *dict = @{@"key": @"value", @"nextKey": @"nextValue"};
NSDictionary voor NSArray
NSDictionary *myDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
NSArray *copiedArray = myDictionary.copy;
Krijg sleutels:
NSArray *keys = [myDictionary allKeys];
Krijg waarden:
NSArray *values = [myDictionary allValues];
NSDictionary voor NSData
NSDictionary *myDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
Reserve pad:
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
NSDictionary voor JSON
NSDictionary *myDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
NSMutableDictionary *mutableDictionary = [myDictionary mutableCopy];
NSData *data = [NSJSONSerialization dataWithJSONObject:myDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
Blokgebaseerde opsomming
Door woordenboeken op te enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block
kunt u een codeblok uitvoeren op elk sleutel / waarde-woordenboekpaar met de methode enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block
Voorbeeld:
NSDictionary stockSymbolsDictionary = @{
@"AAPL": @"Apple",
@"GOOGL": @"Alphabet",
@"MSFT": @"Microsoft",
@"AMZN": @"Amazon"
};
NSLog(@"Printing contents of dictionary via enumeration");
[stockSymbolsDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"Key: %@, Value: %@", key, obj);
}];
Snelle opsomming
NSDictionary
kan worden opgesomd met behulp van snelle opsomming, net als andere soorten verzameling:
NSDictionary stockSymbolsDictionary = @{
@"AAPL": @"Apple",
@"GOOGL": @"Alphabet",
@"MSFT": @"Microsoft",
@"AMZN": @"Amazon"
};
for (id key in stockSymbolsDictionary)
{
id value = dictionary[key];
NSLog(@"Key: %@, Value: %@", key, value);
}
Omdat NSDictionary
inherent ongeordend is, is de volgorde van toetsen die in de for-lus niet is gegarandeerd.
Modified text is an extract of the original Stack Overflow Documentation
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow