2012-11-09 4 views
0

JSON Array 형식으로 제공되는 웹 스토어에서 REST를 통해 카테고리 데이터를 iOS의 코어 데이터로 파싱하려고합니다. 코어 데이터에 삽입하기 전에 출력을 화면에 기록하고 모든 결과를 확인하는 것이 좋습니다. 내 테스트 데이터에NSArray에서 JSON 데이터를 파싱하는 재귀 함수 - 정확한 결과를 반환하지 않음

문제점 그러나 나는 단지 로그에 출력 141의 '최종 카운터'를 얻고, 내가 152 카테고리를 설정?

나는 재귀 함수를 살펴 보았고 ok를 믿었 기 때문에 문제는 findSubcategoriesForCategoryID 함수의 어딘가에 있다고 생각합니까?

문제에 대한 피드백은 이것이 지금 몇 시간 동안 나를 지켜 주었기 때문에 가장 감사 할 것입니다.

예 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]; 
} 
+0

당신은 전체 결과 배열이 아닌 수를 기록해야합니다. 그렇다면 오류가 자명 해져야합니다. – Mundi

답변

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); 
    }  
} 
관련 문제