iPhone-JSONKit-Working,但我用对了吗?

iPhone-JSONKit-Working,但我用对了吗?,iphone,objective-c,Iphone,Objective C,我使用JSONKit进行了一点反序列化。这是工作,但我写的感觉相当笨重。有人能提出一些改进建议吗:) //使用url和员工id调用web服务 NSString*result=[MobileAppDelegate WebServiceExecuteGetIngleWithId:Statffid 自然:“XXXXXXXX”]; //从JSON返回类型创建NSDictionary NSDictionary*items=[result objectFromJSONString]; NSArray*ar=

我使用JSONKit进行了一点反序列化。这是工作,但我写的感觉相当笨重。有人能提出一些改进建议吗:)

//使用url和员工id调用web服务
NSString*result=[MobileAppDelegate WebServiceExecuteGetIngleWithId:Statffid
自然:“XXXXXXXX”];
//从JSON返回类型创建NSDictionary
NSDictionary*items=[result objectFromJSONString];
NSArray*ar=(NSArray*)[items objectForKey:@“SummaryJsonResult”];
对于(int i=0;i<[ar count];i++){
NSDictionary*tmpDict=(NSDictionary*)[ar对象索引:i];
AlertItem*tmpItem=[[AlertItem alloc]init];
tmpItem.Description=[tmpDict objectForKey:@“Description”];
tmpItem.NumItems=[tmpDict objectForKey:@“ItemCount”];
tmpItem.ModuleGroup=[tmpDict objectForKey:@“ModuleGroup]”;
tmpItem.StaffID=[tmpDict objectForKey:@“StaffID]”;
tmpItem.status-[tmpDict objectForKey:@“status”];
[数组addObject:tmpItem];
[tmpItem释放];
}

这就是你必须做的事情。你可以稍微清理一下:

对in循环使用

for (NSDictionary *tmpDict in [items objectForKey:@"SummaryJsonResult"]) {
    ...
将从字典创建的
AlertItem
重构为工厂方法:

+ (AlertItem *)alertItemWithDictionary:(NSDictionary *)dict {
    AlertItem *item = [[self alloc] init];
    ...do the same stuff you do in the loop
    return [item autorelease];
}

... then in the loop you just do:
[array addObject:[AlertItem alertItemWithDictionary:tempDict]];

首先,似乎您正在同步执行请求,这通常是个坏主意。如果您在主线程上运行此命令,则会阻止所有用户交互,直到请求完成


您的代码也不会处理任何格式错误的数据。如果JSON中的任何对象的类型与您预期的不同,您的应用程序将崩溃。如果“SummaryJsonResult”指向字典而不是数组,则在尝试向其发送
objectForKey:
消息时会出现“无法识别的选择器”异常。您可以使用
isKindOfClass:
respondsToSelector:

来防止这种情况,谢谢您的建议。我想知道是否有办法从NSDictionary到NSArray再回到NSDictionary。似乎应该有某种物品可以满足这三种需求?好的,谢谢。我将把它改为异步请求。如果您不知道json的确切格式,有什么特别好的方法可以从json中获取数据吗。我正在调用我自己的web服务,因此我可以控制返回的内容,但如果有其他方法,那就更好了。异步请求的问题是,我正在使用数组填充UITableView,因此如果我执行asyc请求,在填充数据数组之前,它不会开始尝试填充表视图吗?我假设这将导致空指针?您可以将其初始化为空数组。您甚至不必这样做,因为实例变量会自动初始化为nil,并将消息发送到nil(
count
,在本例中)返回0或nil,具体取决于上下文。
+ (AlertItem *)alertItemWithDictionary:(NSDictionary *)dict {
    AlertItem *item = [[self alloc] init];
    ...do the same stuff you do in the loop
    return [item autorelease];
}

... then in the loop you just do:
[array addObject:[AlertItem alertItemWithDictionary:tempDict]];