2010-05-16 2 views

답변

4

어딘가에 pathByJoiningPathComponents 방법이 있거나 적어도 하나는 좋아할 것이라고 맹세했지만 나는 다른 것을 생각하고 있어야합니다. 이것은 당신이 10.6 있다면 그것은 (난 단지 경로와 그것을 테스트) 너무 URL에 대한 작동 할 수 경로에 대한 트릭을 수행합니다 나는 없다고 생각

NSString *path1 = @"/path/to/file1.txt"; 
NSString *path2 = @"/path/to/file/number2.txt"; 

NSArray *path1Comps = [path1 pathComponents]; 
NSArray *path2Comps = [path2 pathComponents]; 

NSUInteger total = [path1Comps count]; 
if ([path2Comps count] < total) 
    total = [path2Comps count]; // get the smaller of the two 

NSUInteger i; 
for (i = 0; i < total; i++) 
    if (![[path1Comps objectAtIndex:i] isEqualToString:[path2Comps objectAtIndex:i]]) 
     break; 

NSArray *commonComps = [path1Comps subarrayWithRange:NSMakeRange(0, i)]; 

// join commonComps together to get the common path as a string 

을 “ 내장 ” 방식 불행하게도. 당신이 공통 조상을 찾으려는 파일 경로의 배열이있는 경우

, 당신이 뭔가를 할 수 있습니다 :

NSArray *allPaths = [NSArray arrayWithObjects:@"/path/to/1.txt", @"/path/to/number/2.txt", @"/path/to/number/3/file.txt", nil]; 

// put some checks here to make sure there are enough paths in the array. 

NSArray *currentCommonComps = [[allPaths objectAtIndex:0] pathComponents]; 

for (NSUInteger i = 1; i < [allPaths count]; i++) 
{ 
    NSArray *thisPathComps = [[allPaths objectAtIndex:i] pathComponents]; 
    NSUInteger total = [currentCommonComps count]; 
    if ([thisPathComps count] < total) 
     total = [thisPathComps count]; 

    NSUInteger j; 
    for (j = 0; j < total; j++) 
     if (![[currentCommonComps objectAtIndex:j] isEqualToString:[thisPathComps objectAtIndex:j]]) 
      break; 

    if (j < [currentCommonComps count]) 
     currentCommonComps = [currentCommonComps subarrayWithRange:NSMakeRange(0, j)]; 

    if ([currentCommonComps count] == 0) 
     break; // no point going on 
} 

// join currentCommonComps together 

당신은 명시 적으로 할당하고 원하는 경우 이러한 개체 중 일부를 해제 할 수 있습니다 autorelease 풀을 깨끗하게 유지하려면 특히 경로가 많은 경우에 유용합니다.

+0

와우! 이것은 굉장합니다! 두 개 이상의 파일 경로를 사용하면 어떻게 할 수 있습니까? (이 질문에 대해 투표하십시오. 현상금에 내 대리인을 사용했습니다.) –

+0

답변을 업데이트했습니다. 그것은 꽤 아니지만, 할 일이 무엇인지에 대한 아이디어를 줄 것입니다. 이것은 내가 말할 수있는 한 O (n^2)입니다. 아마도 더 최적의 솔루션이있을 것입니다. – dreamlax

+0

NSString은'pathWithComponents :'클래스 메소드를 가지고 있습니다. –

1

파일을 가져 와서 다음 파일을 가져 와서 공통된 항목을 찾을 때까지 해당 조상을 반복합니다 (NSString의 pathComponents 메서드는 유용 할 것입니다). 다음 파일로 이동하여 동일한 조상이 있는지 확인하십시오. 그렇지 않다면 그들이 공통점이있는 것을 찾을 때까지 계속 돌아가십시오. 목록의 끝에 도달 할 때까지이 작업을 반복하십시오.

2

구성 요소의 NSArrays로 경로를 나타냅니다. (Mac OS X 10.6 이상에서는 각 객체에 pathComponents 메시지를 보내고 이전 버전 및 iPhone OS에서는 NSString을 가져 오기 위해 path 메시지를 NSURL 객체로 보내야합니다.

지금까지 공통 경로를 포함하는 NSMutableArray가 있습니다. 첫 번째 경로의 구성 요소로 초기화하십시오.

각 후속 경로의 경우 NSEnumerator를 사용하여 잠금 단계에서 현재 경로와 현재 경로를 반복합니다.

  • 지금까지 공통 경로에 도달하면 변경되지 않습니다.
  • 검사중인 경로가 모두 소모되면 새 공통 경로입니다.
  • 부등 구성 요소가 발견되면 그 이전의 모든 구성 요소는 새 공통 경로입니다. 잠금 단계 반복을 여기서 중단하십시오.

완료하면 0 개 이상의 경로 구성 요소 배열을 갖게됩니다. 이들을 절대 경로 문자열에 결합하면 공통 경로 문자열이 생성됩니다.