EDIT_v002
我已经看过了所有的评论,我开始明白我应该做什么。为此,我修改了我的代码(见下文),我将newPath更改为NSString,删除了[alloc init]和end发行版,因为它现在由系统处理。我正在使用stringByAppendingPathComponent,让它在rootPath和fileName之间添加一个分隔符,然后再将其分配给NSString。它确实起作用了,我通过静态分析器运行了它,没有出现任何问题。
// ------------------------------------------------------------------- **
// DISC: FILEWALKER ..... (cocoa_fileWalker.m)
// DESC: List all "*.png" files in specified directory
// ------------------------------------------------------------------- **
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *fileName;
NSDictionary *attrDir;
NSError *myError;
NSNumber *fileSize;
NSFileManager *manager = [NSFileManager defaultManager];
NSString *rootPath = [@"~/Pictures/Ren/PRMan" stringByExpandingTildeInPath];
NSString *newPath;
NSLog(@"Home: %@",rootPath);
for(fileName in [manager enumeratorAtPath:rootPath]){
if ([[fileName pathExtension] isEqual:@"png"]) {
newPath = [rootPath stringByAppendingPathComponent:fileName];
attrDir = [manager attributesOfItemAtPath:newPath error:&myError];
fileSize = [attrDir objectForKey: @"NSFileSize"];
NSLog(@"File: %@ Size: %@", newPath, fileSize);
}
}
[pool drain];
return 0;
}
// ------------------------------------------------------------------- **加里
发布于 2009-09-29 03:02:04
stringByAppendingPathComponent,它是如何工作的?
很简单。您想要附加一个路径组件。将该消息发送到要附加路径组件的字符串,并传递要附加的路径组件。
路径组件不是斜杠;如果它们是斜杠,pathComponents方法将只返回一个斜杠数组。路径组件是斜杠之间的部分(尽管在pathComponents的定义中描述了一种特殊情况)。
斜杠是路径分隔符。这在Cocoa中是硬编码的;它目前(并且可能总是)是一个斜杠。因此,如果您真的想要在字符串中附加一个斜杠,最有可能的原因是您想要附加一个路径分隔符,而不是路径组件。
[newPath setString:rootPath]; [newPath appendString:@"/"]; [newPath appendString:fileName];
fileName是您要添加的组件。使用stringByAppendingPathComponent:并传递fileName,而不是斜杠。
至于你的例子是否泄露了:那么,一个对象在没有释放的情况下会不会超出范围?这个问题的答案就是它是否是泄漏的答案。如果您不确定,请查看the memory management rules。
发布于 2009-09-28 21:45:36
您不需要附加分隔符。添加下一个路径部分(如filename、dir等)。这避免了您需要知道特定系统的分隔符。
NSMutableString* mutablePath = [NSMutableString string];
NSString* fullPath = [rootPath stringByAppendingPathComponent:filename];
[mutablePath setString:fullPath]; // OK to setString: of Mutable with non-Mutable
[mutablePath appendString:someOtherString]; // This won't cause an exception
// Example to clarify on comments below
{
// This will cause a compiler warning.
// warning: incompatible Objective-C types assigning
// ‘struct NSString *’, expected ‘struct NSMutableString *’
NSMutableString* ms = [@"FOO" stringByAppendingPathComponent:@"BAR"];
}在the documentation.中有一个相当清晰的例子
发布于 2009-09-28 22:15:32
所有现有的答案都泄漏了原始的testPath字符串。对于这么简单的东西,为什么没有人推荐-[NSMutableString appendString:] intead呢?
[testPath appendString:@"/"];对于NSMutableString,没有等同于-stringByAppendingPathComponent:的东西,但看起来他只是想添加一个斜杠,而不是路径组件。如果你真的想添加一个路径组件,你可以这样做:
[testPath setString:[testPath stringByAppendingPathComponent:@"..."]];这是一个恼人的变通方法,但正如@dreamlax指出的那样,即使在NSMutableString对象上调用,-stringByAppendingPathComponent:也总是返回一个不可变的字符串。:-(
https://stackoverflow.com/questions/1489522
复制相似问题