Objective-C for Dummies:如何在NSDictionary内部循环NSDictionary?

时间:2011-02-08 04:42:20

标签: objective-c xcode ios

好吧,伙计们,我很困惑。所以,我有一个NSDictionary,它由一个JSON字符串填充,如下所示:

{"Success":true,"Devices":[{"UDId":"...","User":"...","Latitude":0.0,"Longitude":0.0}]}

现在,我知道如何检查Success是否为true,但是我需要遍历Devices(JSON对象)数组并创建一个{{1}的内部数组(内部应用程序对象),我不知道该怎么做。有人可以解释一下怎么做吗?

这是我的Devices

Device.m/h

以下是我应该阅读响应并将其转换为我可以使用的对象的方法:

#import <CoreLocation/CoreLocation.h>
#import <Foundation/Foundation.h>

@interface Device : NSObject {
    NSString *udId;
    NSString *name;
    NSNumber *latitude;
    NSNumber *longitude;
}

@property (nonatomic, retain) NSString *udId;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSNumber *latitude;
@property (nonatomic, retain) NSNumber *longitude;

#pragma mark -
#pragma mark MKAnnotation Properties
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

@end

----

#import "Device.h"

@implementation Device

@synthesize udId, name, latitude, longitude;

- (CLLocationCoordinate2D)coordinate {
    CLLocationCoordinate2D internalCoordinate;

    internalCoordinate.latitude = [self.latitude doubleValue];
    internalCoordinate.longitude = [self.longitude doubleValue];

    return internalCoordinate;
}

- (void)dealloc {
    [udId release];
    udId = nil;

    [name release];
    name = nil;

    [latitude release];
    latitude = nil;

    [longitude release];
    longitude = nil;

    [super dealloc];
}

@end

我真的很感激这方面的一些帮助。我似乎无法绕过它......

提前致谢!

4 个答案:

答案 0 :(得分:3)

你快到了。在您的代码中,您说:

  //  READ "DEVICES" AND CONVERT TO OBJECTS

这样做:

  NSArray * devices = [jsonDictionary objectForKey:@"Devices"];
  for(NSDictionary * deviceInfo in devices) {
    Device * d = [[[Device alloc] init] autorelease];
    [d setLatitude:[deviceInfo objectForKey:@"Latitude"]];
    [d setLongitude:[deviceInfo objectForKey:@"Longitude"]];
    [d setName:[deviceInfo objectForKey:@"User"]];
    [d setUdId:[deviceInfo objectForKey:@"UDId"]];
    // do some stuff with d
  }

这里发生了什么:我没有看到您使用的JSON库进行转换,但假设它的工作方式与TouchJSON或SBJSON类似,则JSON数组会自动转换为NSArray实例,而NSArray的内部哈希值则为NSDictionary对象。在您对该JSON字符串进行反序列化时,您所处理的所有内容都将是NSString,NSNumber,NSArray和NSDictionary的实例(并且取决于库,NSNull表示空值)。

答案 1 :(得分:1)

首先,您需要为Device类定义初始化程序/构造函数。

device.h中

- (id)initWithUdid:(NSString *)udid name:(NSString *)name latitude:(NSNumber *)lat longitude:(NSNumber *)lon;

Device.m

- (id)initWithUdid:(NSString *)udid name:(NSString *)name latitude:(NSNumber *)lat longitude:(NSNumber *)lon {
    if (self = [super init]) {
        self.udid = udid;
        self.name = name;
        self.latitude = lat;
        self.longitude = lon;
    }
    return self;
}

然后您可以初始化一个新对象,如:

Device *dev = [[Device alloc] initWithUdid:@"a udid" name:@"the name" latitude:latNum longitude:lonNum];

因此,您应该能够迭代数组并构建您的Device对象,如下所示:

NSArray *devicesArray = [dict objectForKey:@"Devices"];
for (NSDictionary *d in devicesArray) {
  Device *dev = [[Device alloc] initWithUdid:[d objectForKey:@"UDId"]
                                        name:[d objectForKey:@"User"]
                                    latitude:[NSNumber numberWithDouble:[d objectForKey:@"Latitude"]]
                                   longitude:[NSNumber numberWithDouble:[d objectForKey:@"Latitude"]]];
}

答案 2 :(得分:0)

您希望从顶级字典访问设备字典数组,就像访问Success值一样。然后迭代字典,您可以使用每个-keyEnumerator方法迭代其键。

- (void)requestFinished:(ASIHTTPRequest *)request {
    if (![request error]) {
        NSError *jsonError = nil;
        NSDictionary *jsonDictionary = [NSDictionary dictionaryWithJSONString:[request responseString] error:&jsonError];

        if (!jsonError || ([[jsonDictionary objectForKey:@"Success"] intValue] == 1)) {
            NSArray* deviceArray = [jsonDictionary objectForKey:@"Devices"];
            for(NSDictionary* dict in deviceArray)
            {
                for(NSString* key in [dict keyEnumerator])
                {
                    NSLog(@"%@ -> %@", key, [dict objectForKey:key]);
                }
            }
            //  READ "DEVICES" AND CONVERT TO OBJECTS
        } else {
            //  AUTHORIZATION FAILED
        }
    }
}

答案 3 :(得分:0)

听起来你需要重复使用你的行:

[jsonDictionary objectForKey:@"Success"]

试着看看

[jsonDictionary objectForKey:@"Devices"]

你真的需要弄清楚它返回的是什么类型。 如果你很幸运,它会返回一个NSDictionary,或者你可以很容易地变成NSDictionary的东西。