【发布时间】:2014-05-01 19:52:16
【问题描述】:
我的解析云代码函数设置为以 JSON 形式返回数据,如下所示:
response.success
({
"results": [
{ "Number of top categories": top2.length },
{ "Top categories": top2 },
{ "Number of matches": userCategoriesMatchingTop2.length },
{ "User categories that match search": userCategoriesMatchingTop2 }
]
});
我想做的是在我的 Objective-C 代码中查询这个 JSON 数组,并通过使用底部的 if 语句根据返回的内容执行某些操作。例如,它说:
if ([result intValue] == 1){
[self performSegueWithIdentifier:@"ShowMatchCenterSegue" sender:self];
}
我想用一条语句替换result intValue,说明 JSON 数据中“匹配数”的值等于 1。
- (IBAction)nextButton:(id)sender
{
if (self.itemSearch.text.length > 0) {
[PFCloud callFunctionInBackground:@"eBayCategorySearch"
withParameters:@{@"item": self.itemSearch.text}
block:^(NSString *result, NSError *error) {
NSLog(@"'%@'", result);
NSData *returnedJSONData = result;
NSError *jsonerror = nil;
NSDictionary *categoryData = [NSJSONSerialization
JSONObjectWithData:returnedJSONData
options:0
error:&jsonerror];
if(error) { NSLog(@"JSON was malformed."); }
// validation that it's a dictionary:
if([categoryData isKindOfClass:[NSDictionary class]])
{
NSDictionary *jsonresults = categoryData;
/* proceed with jsonresults */
}
else
{
NSLog(@"JSON dictionary wasn't returned.");
}
if (!error) {
// if 1 match found clear categoryResults and top2 array
if ([result intValue] == 1){
[self performSegueWithIdentifier:@"ShowMatchCenterSegue" sender:self];
}
// if 2 matches found
else if ([result intValue] == 2){
[self performSegueWithIdentifier:@"ShowUserCategoryChooserSegue" sender:self];
//default to selected categories criteria -> send to matchcenter -> clear categoryResults and top2 array
}
// if no matches found, and 1 top category is returned
else if ([result intValue] == 2) {
[self performSegueWithIdentifier:@"ShowCriteriaSegue" sender:self];
}
// if no matches are found, and 2 top categories are returned
else if ([result intValue] == 2) {
[self performSegueWithIdentifier:@"ShowSearchCategoryChooserSegue" sender:self];
}
}
}];
}
}
【问题讨论】:
-
使用间接返回
NSError的方法时,Cocoa要求在使用NSError之前检查直接返回值,而不是错误是否为nil。如果方法指示失败,错误是 guaranteed 是有效的,但相反的 - 它将是nil成功 - not 保证,即使你将它设置为 @987654330事先@。 -
您遇到了什么问题?您需要知道结果字典中有多少项?完全不清楚您所说的“匹配数”是什么意思。
-
如果你看一下我返回的 JSON,
"Number of matches"是其中一个键,它的值是从我的云代码中的userCategoriesMatchingTop2数组的长度得出的。在这种情况下,如果userCategoriesMatchingTop2.length等于 1,我想告诉我的 iOS 应用执行某个操作。 -
实现这一目标您面临的困难是什么?
-
我不确定如何形成执行此操作所需的语法。我查看了 NSDictionary 文档,但不清楚我将如何处理这种特殊情况。
标签: ios objective-c json nsdictionary