xcode Objective-C for Dummies:如何在 NSDictionary 中循环遍历 NSDictionary?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4929624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C for Dummies: How do I loop through an NSDictionary inside of an NSDictionary?
提问by Gup3rSuR4c
Alright guys, I'm quite confused. So, I have an NSDictionary which is populated by a JSON string which looks like:
好吧,伙计们,我很困惑。所以,我有一个 NSDictionary,它由一个 JSON 字符串填充,如下所示:
{"Success":true,"Devices":[{"UDId":"...","User":"...","Latitude":0.0,"Longitude":0.0}]}
Now, I know how to check if Success
is true
, but I need to loop through the array of Devices
(JSON object) and create an internal array of Devices
(internal app object) and I have no idea how to do that. Can someone please explain how to do it?
现在,我知道如何检查 if Success
is true
,但我需要遍历Devices
(JSON 对象)的数组并创建Devices
(内部应用程序对象)的内部数组,但我不知道该怎么做。有人可以解释一下怎么做吗?
Here's my Device.m/h
:
这是我的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
And here's the methods where I should be reading the response and converting it to objects I can use:
这是我应该读取响应并将其转换为我可以使用的对象的方法:
- (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
}
}
}
I'd really appreciate some help on this. I just can't seem to wrap my head around it...
我真的很感激这方面的一些帮助。我似乎无法绕过它......
Thanks in advance!
提前致谢!
采纳答案by raidfive
First you need to define your initializer/constructor for your Device class.
首先,您需要为 Device 类定义初始化程序/构造函数。
Device.h
设备文件
- (id)initWithUdid:(NSString *)udid name:(NSString *)name latitude:(NSNumber *)lat longitude:(NSNumber *)lon;
Device.m
设备.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;
}
Then you can initialize a new object like:
然后你可以初始化一个新对象,如:
Device *dev = [[Device alloc] initWithUdid:@"a udid" name:@"the name" latitude:latNum longitude:lonNum];
So, you should be able to iterate the array and build your Device objects like so:
因此,您应该能够迭代数组并构建您的设备对象,如下所示:
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"]]];
}
回答by Chris Zelenak
You are almost there. In your code where you say:
你快到了。在您的代码中,您说:
// READ "DEVICES" AND CONVERT TO OBJECTS
do this:
做这个:
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
}
What's going on here: I didn't see what JSON library you are using to convert, but presuming it works like TouchJSON or SBJSON, the JSON array is automatically turned into an NSArray instance, while the inner hashes of the NSArray are NSDictionary objects. At the point that you have deserialized that JSON string, everything you're dealing with will be instances of NSString, NSNumber, NSArray and NSDictionary (and depending on the library, NSNull to represent null values).
这是怎么回事:我没有看到您使用什么 JSON 库进行转换,但假设它像 TouchJSON 或 SBJSON 一样工作,JSON 数组会自动转换为 NSArray 实例,而 NSArray 的内部哈希是 NSDictionary 对象。在您反序列化该 JSON 字符串时,您处理的所有内容都将是 NSString、NSNumber、NSArray 和 NSDictionary 的实例(并且取决于库,NSNull 表示空值)。
回答by nall
You want to access the array of device dictionaries from the top-level dictionary just as you did the Success value. Then iterating over the dictionaries you can use each's -keyEnumerator
method to iterate over its keys.
您希望像访问 Success 值一样访问顶级字典中的设备字典数组。然后迭代字典,您可以使用 each 的-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
}
}
}
回答by Rick
Sounds like you need to reuse your line:
听起来您需要重用您的线路:
[jsonDictionary objectForKey:@"Success"]
try having a look at
试试看
[jsonDictionary objectForKey:@"Devices"]
You really need to figure out what type it returns.
If you're lucky, it returns an NSDictionary
, or alternately something that you can easily turn into an NSDictionary
.
你真的需要弄清楚它返回什么类型。如果幸运的话,它会返回一个NSDictionary
,或者您可以轻松地将其转换为NSDictionary
.