繁体   English   中英

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

[英]Objective-C for Dummies: How do I loop through an NSDictionary inside of an NSDictionary?

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

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

现在,我知道如何检查Success是否为true ,但我需要遍历Devices (JSON对象)数组并创建一个内部Devices数组(内部app对象),我不知道如何做到这一点。 有人可以解释一下怎么做吗?

这是我的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

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

- (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)) {
            //  READ "DEVICES" AND CONVERT TO OBJECTS
        } else {
            //  AUTHORIZATION FAILED
        }
    }
}

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

提前致谢!

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

  //  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表示空值)。

首先,您需要为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"]]];
}

您希望从顶级字典访问设备字典数组,就像执行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
        }
    }
}

听起来你需要重用你的线:

[jsonDictionary objectForKey:@"Success"]

试着看看

[jsonDictionary objectForKey:@"Devices"]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM