我正在尝试将通过 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];
}