0

我正在尝试将通过 REST 以 JSON 数组格式提供的网上商店中的类别数据解析为 iOS 上的核心数据。在我开始插入核心数据之前,我只是将输出记录到屏幕上并记录结果以检查一切是否正常。

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

我查看并查看了递归函数并相信它没问题,因此我认为问题出在 findSubcategoriesForCategoryID 函数的某个地方?

任何有关该问题的反馈都将不胜感激,因为这已经让我好几个小时了。

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

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];
}
4

1 回答 1

0

您的递归函数看起来不错,但它相当复杂,因此只有测试才能保证它确实适用于所有特殊情况。

如果我正确理解了您的算法,您将从顶部开始,然后向下查找以当前 ID 作为父 ID 的项目。因此,您可能有不作为类别 id 存在的父 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); 
   }      
}
于 2012-11-09T15:49:14.083 回答