递归函数从NSArray解析JSON数据 - 未返回正确数量的结果



我正在尝试通过以JSON数组格式为iOS上的核心数据从网络存储中解析类别数据。在开始插入核心数据之前,我只是将输出记录到屏幕上,并保留结果数以检查所有内容。

问题在我的测试数据集中我有 152 类别,但是我只得到 141 输出的"最终计数器"日志?

我看了看递归功能并相信它可以,因此我认为问题在于findsubcategoriesforcategoryid函数中的某个地方?

关于该问题的任何反馈都将最感激,因为这使我现在已经持续了几个小时。

示例JSON数据从Web服务返回:

Node: {
    categoryID = 259;
    categoryTitle = "Engine Parts";
    parentID = 0;   // Parent ID of 0 indicates a root category
}
Node: {
    categoryID = 300;
    categoryTitle = "Camshafts";
    parentID = 259; // Parent ID indicates this category is a subcategory
}
Node: {
    categoryID = 317;
    categoryTitle = "Kent Camshafts";
    parentID = 300;
} 

以下方法是我应用程序中所拥有的。

/**
 *   Kickstarts parsing operation
 */
- (void)parseCategoriesData:(NSArray *)downloadedData {
    NSMutableDictionary *fakeCategory = [NSMutableDictionary dictionary];
    [fakeCategory setObject:[NSNumber numberWithInt:0] forKey:@"categoryID"];
    int counter = 0;
    [self recursiveFunction:downloadedData parentCategory:fakeCategory counter:&counter];
    NSLog(@"Final counter = %d", counter);
}
/**
 *   Recursive function to traverse the passed NSArray
 */
- (void)recursiveFunction:(NSArray *)array parentCategory:(id)parentCategory counter:(int *)i {    
    NSArray *subCategories = [self findSubcategoriesForCategoryID:[[parentCategory valueForKey:@"categoryID"] intValue] categoryData:array];
    for (id object in subCategories) {
        NSLog(@"Node: %@  depth: %d",[object description], *i);
        *i = *i + 1;
        [self recursiveFunction:array parentCategory:object counter:i];
    }
}
/**
 *   Returns an NSArray of subcategories for the passed categoryID
 */
- (NSArray *)findSubcategoriesForCategoryID:(int)categoryID categoryData:(NSArray *)categoryData {
    NSIndexSet *indexsForFilteredCategories = [categoryData indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
        return (BOOL)([[obj valueForKey:@"parentID"] intValue] == categoryID);
    }];
    return [categoryData objectsAtIndexes:indexsForFilteredCategories];
}

您的递归功能看起来还不错,但是它相当令人费解,因此只有测试才能保证它确实适用于所有特殊情况。

如果我正确理解您的算法,则从顶部开始,然后转到具有当前ID作为父ID的项目。您可能拥有不存在类别IDS 的父级ID。

这很容易测试:

NSArray *allIDs = [downloadedData objectForKey:@"categoryID"];
NSArray *allParentIDs = [downloadedData objectForKey:@"parentID"];
for (NSNumber *x in allParentIDs) {
   if (x.intValue==0) continue;
   NSArray *allChildren = [allIDs filteredArrayUsingPredicate:
     [NSPredicate predicateWithFormat:@"self = %@", x]];
   if (allChildren.count == 0) {
      NSLog(@"There are no category ids for parent id %d.", x.intValue); 
   }      
}

最新更新