I've found a lot of documentation about how to code data into a key => value
style, but how do i go about extracting the key & value from an array? I'm currently using NSArray
.
What i'm after is the obj-c equivlant to php's foreach($array as $k => $v)
What are you looking for is NSDictionary. NSArray is accessible via indexes: 0, 1, 2 etc:
NSDictionary could be accessed like dict[@"key"]
or [dict objectForKey:@"key"];
So, accessing NSArray would be:
for( int i = 0; i < [someArray count]-1; i++)
{
NSLog(@"%@", someArray[i]);
}
while accessing your NSDictionary would be:
for (NSString* key in yourDict) {
NSLog(@"%@", yourDict[key]);
//or
NSLog(@"%@", [yourDict objectForKey:key]);
}
An NSArray is like this :
NSArray *array = @[@"One", @"Two", @"Three"];
//Loop through all NSArray elements
for (NSString *theString in array) {
NSLog(@"%@", theString);
}
//Get element at index 2
NSString *element = [array objectAtIndex:2];
//Or :
NSString *element = array[2];
If you have an object and you what to find its index in the array (object must be unique in array, otherwise will only return the first found) :
NSUInteger indexOfObject = [array indexOfObject:@"Three"];
NSLog(@"The index is = %lu", indexOfObject);
But if you are working with keys and values, maybe you need a NSDictionary.
An NSDictionary is like this :
NSDictionary *dictionary = @{@"myKey": @"Hello World !",
@"other key": @"What's up ?"
};
//Loop NSDictionary all NSArray elements
for (NSString *key in dictionary) {
NSString *value = [dictionary valueForKey:key];
NSLog(@"%@ : %@", key, value);
}
If u are having NSArray having number of dictionaries then u can get them as below
for(NSDictionary *dict in yourArray)
{
NSLog(@"The dict is:%@",dict);
NSLog(@"The key value for the dict is:%@",[dict objectForKey:@"Name"]);//key can be changed as per ur requirement
}
///(OR)
[yourdict enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
NSLog(@"Key -> value of Dict is:%@ = %@", key, object);
}];
Hope it helps you...!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.