2009-09-28 43 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 &分析器來讓Clang檢查這種事情。

請記住,您只需發佈您分配,新增,複製或保留的內容。

考慮使用stringByAppendingPathComponent,而不是硬編碼@"/"路徑分隔符。 NSString有一個number of methods這樣專門用於處理路徑。

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

嗯我嘗試添加[NEWPATH stringByAppendingPathComponent:@ 「/」];要測試添加「/」的結尾,但我似乎無法得到它的工作... – fuzzygoat 2009-09-28 21:22:46

+0

stringByAppendingPathComponent避免你必須知道分隔符。我已經更新了答案以反映使用情況。 – nall 2009-09-28 21:39:56

+0

謝謝,那它怎麼知道要添加什麼? – fuzzygoat 2009-09-28 21:44:41

1

沒有什麼不對的地方,但它可能是最好使用initWithFormat和釋放:

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

// do your thing 

[newPath release]; 
+1

沒有提到但很重要:這將會進入循環。 – Chuck 2009-09-28 19:56:24

+0

謝謝,來自程序編程我總是有點小心謹慎地聲明變量按需(即不是在一個塊的開始)我想我只需要更靈活一點,更多的開放視圖關於Objective- C – fuzzygoat 2009-09-28 21:00:51

+2

事實上,在最封閉的範圍內(即最接近它們使用的地方)聲明變量有很好的理由。 – nall 2009-09-28 21:41:14

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

謝謝,非常感謝。 – fuzzygoat 2009-09-29 20:45:00

相關問題