2009-09-28 4 views
3

이 작업을 수행하는 방법이 궁금한 경우 그냥 누수가 없는지 확인하고 싶지만 문자열 내용 만 수정한다고 생각합니다.루프에서 문자열을 작성/삭제하는 올바른 방법입니까?

NSMutableString *newPath = [[NSMutableString alloc] init]; 

for(fileName in [manager enumeratorAtPath:rootPath]){ 
    if ([[fileName pathExtension] isEqual:@"exr"]) { 
     [fileArray addObject:fileName]; 

     // THIS BIT 
     [newPath setString:rootPath]; 
     [newPath appendString:@"/"]; 
     [newPath appendString:fileName]; 
     // HERE 
     attrDir = [manager attributesOfItemAtPath:newPath error:&myError]; 

     fileSize = [attrDir objectForKey: @"NSFileSize"]; 
     NSLog(@"File: /%@ Size: %@", fileName, fileSize); 
    } 
} 
[newPath release]; 

게리가

답변

7

이 누출 현명한 잘 보인다. Xcode 3.2를 실행중인 경우 Build-> Build & Analyzer를 사용하여 Clang이 이런 종류의 것을 검사하도록 할 수 있습니다.

할당 한 항목을 릴리스하거나 새로 작성하거나 복사하거나 보유해야한다는 것을 기억하십시오.

@"/" 경로 구분 기호를 하드 코딩하는 대신 stringByAppendingPathComponent을 사용하는 것이 좋습니다. NSString에는 number of methods이 있습니다. 특별히 경로 작업에 사용됩니다. 코드 아무 문제가 전혀 없다

NSString *newPath = [[NSString alloc] initWithFormat:@"%@/%@",rootPath,fileName]; 

// do your thing 

[newPath release]; 
+0

흠 내가 추가하는 시도 [newpath를 stringByAppendingPathComponent : @ "/"]; 끝 부분에 "/"를 추가하여 테스트 할 수 있지만 제대로 작동하지 않는 것 같습니다 ... – fuzzygoat

+0

stringByAppendingPathComponent는 구분 기호에 대해 알 필요가 없도록합니다. 사용법을 반영하도록 답변을 업데이트했습니다. – nall

+0

감사합니다. 그래서 무엇을 추가해야할지 어떻게 알 수 있습니까? – fuzzygoat

1

, 그것은 아무 문제가 없습니다.

그러나 필요도 적은 코드 및 메모리 관리를 수행 할 수 있습니다

for(fileName in [manager enumeratorAtPath:rootPath]){ 
    if ([[fileName pathExtension] isEqualToString:@"exr"]) { 
    [fileArray addObject:fileName]; 

    NSString* newPath = [rootPath stringByAppendingPathComponent:fileName]; 
    attrDir = [manager attributesOfItemAtPath:newPath error:&myError]; 

    fileSize = [attrDir objectForKey: @"NSFileSize"]; 
    NSLog(@"File: /%@ Size: %@", fileName, fileSize); 
    } 
} 
+1

언급되지 않았지만 중요합니다. – Chuck

+0

절차 형 프로그래밍에서 오는 감사합니다. 저는 항상 요구 사항에 따라 변수를 선언하는 것에 약간주의를 기울입니다. 즉, 블록 시작 부분이 아닌 변수를 선언하는 것입니다. Objective- C – fuzzygoat

+2

사실, 가장 포괄적 인 범위에서 변수를 선언 할 수있는 아주 좋은 이유가 있습니다 (즉, 변수가 사용되는 곳과 가장 가까운). – nall

1

, 그것은 올바른 메모리 관리 : initWithFormat를 사용하고 해제하는 것이 더있을 수 있지만

NSString* fullPath = [rootPath stringByAppendingPathComponent:fileName]; 
+0

감사합니다. 많은 감사를드립니다. – fuzzygoat

관련 문제