gpt4 book ai didi

objective-c - 用于假人的Objective-C:如何在NSDictionary内部循环浏览NSDictionary?

转载 作者:行者123 更新时间:2023-12-01 18:33:29 25 4
gpt4 key购买 nike

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

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

现在,我知道如何检查 Success是否为 true,但是我需要遍历 Devices(JSON对象)数组并创建内部 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

这是我应该读取响应并将其转换为可以使用的对象的方法:
- (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
}
}
}

我真的很感谢您的帮助。我只是似乎无法包住头...

提前致谢!

最佳答案

首先,您需要为Device类定义初始化器/构造器。

设备.h

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

设备号
- (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"]]];
}

关于objective-c - 用于假人的Objective-C:如何在NSDictionary内部循环浏览NSDictionary?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4929624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com