Hi I was going through the AFNetworking Tutorial on Ray Wenderlich blog and in this tutorial project he has written a few categories to extend the NSDictionary and one of the category looks like below:
#import "NSDictionary+weather_package.h"
@implementation NSDictionary (weather_package)
- (NSDictionary *)currentCondition
{
NSDictionary *dict = self[@"data"];
NSArray *ar = dict[@"current_condition"];
return ar[0];
}
- (NSDictionary *)request
{
NSDictionary *dict = self[@"data"];
NSArray *ar = dict[@"request"];
return ar[0];
}
- (NSArray *)upcomingWeather
{
NSDictionary *dict = self[@"data"];
return dict[@"weather"];
}
@end
I know for what the categories are used for in Objective-C. But really the code which he has written seems very high level to me and it's confusing. BTW I'm talking about these lines :
NSDictionary *dict = self[@"data"];
NSArray *ar = dict[@"current_condition"];
I'm really not understanding how self[@"data"] and dict[@"current_condition"] work.
So could someone please help me understand what's happening here ? It would be greatly helpful to me.
PS: BTW this is how Ray is calling his category method is called on dictionary :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"WeatherCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *daysWeather = nil;
switch (indexPath.section) {
case 0: {
daysWeather = [self.weather currentCondition];
break;
}
default:
break;
}
Thanks in advance.
This line:
NSDictionary *dict = self[@"data"];
Is just a nice shortcut for :
NSDictionary *dict = [self objectForKey:@"data"];
Where the "data" is the key and the value is a NSDictionary
object.
Same goes with the other line only that the returned value is an array.