2014-02-26 3 views
0

NSMutableArrays의 NSMutableArray에 사전 순으로 정렬 된 NSStrings의 NSArray를 분할하는 방법을 알고 싶습니다. 예를 들어정렬 된 NSStrings의 NSArray를 NSMutableArrays의 NSMutableArray로 분할하는 방법

내가 그것이 가장 가능성에 대한 사용하여 수행 할 필요가 이해이

-- Alice 
    Awesome 

-- Bacon 
    Beef 

-- Hat 
    Hooters 
    Horse 

처럼 보이게 NSMutableArrays의 NSMutableArray를 싶습니다 내 NSArray를이

Alice 
Awesome 
Bacon 
Beef 
Hat 
Hooters 
Horse 

과 같은 말 for 루프 그러나 첫 번째 문자를 잡는 방법을 모르겠다.

내가이 꺼져 있고 루프 로직의 해제 방법을 알고

NSMutableArray *mainArray = [NSMutableArray alloc] init]; 

for (int i = 0; i < [sortedArray count]; i++) { 
    NSMutableArray *subArray = [NSMutableArray alloc] init]; 
    NSString *currentString = [sortedArray objectAtIndex:i]; 

    if (figure out if first character of currentString is what it is supposed to be){ 
    [subArray addObject:currentString]; 
    } 

    [mainArray addObject:subArray]; 
} 

함께 온 의사 코드입니다 ..하지만 난 문제를 겪고 곳과 첫 글자를 찾는 것은 .. 모든 것이 자동으로 모든 일을 처리하는 빠른 대리자 메서드라는 것을 알고 있지만 이것이 내가 질문 한 이유입니다.

어떤 도움을 주시면 감사하겠습니다.

+0

[documentation] (https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html)을 참조하십시오. 'characterAtIndex'는 NSString으로부터 문자를 가져옵니다. –

답변

1
NSString* currentLetter; 
NSMutableArray* currentSubArray; 

for(NSString* name in sortedArray){ 

    NSString* firstLetterOfName = [name substringToIndex:1]; 

    if([firstLetterOfName isEqualToString:currentLetter]){ 
     // Name first letter is equal to the last one, so just add to current sub array 
     [currentSubArray addObject:name]; 
    } 
    else{ 
     // New letter found, create a new sub array and add to main one 

     currentSubArray = [[NSMutableArray alloc] initWithObjects:name, nil]; // needs nil 
     currentLetter = firstLetterOfName; 
     [mainArray addObject:currentSubArray]; 
    } 

} 

뭔가?

+0

이 작동하고 코드가 누락되었습니다. 무리 감사! – HurkNburkS

+0

좋습니다! 다행히 도울 수있어. –

0

과정의 핵심은 다음과 같습니다 그런

unichar ch = [currentString characterAtIndex:0]; 
관련 문제