3

我使用以下代码替换文件的扩展名:

NSString *fileOriginal = [url lastPathComponent];
NSString *fileSource = @"";
NSRange range = [fileOriginal rangeOfString:@"." options:NSBackwardsSearch];
if (range.length > 0) {
    range.length = fileOriginal.length - range.location;
    fileSource = [fileOriginal stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@".%@", @"cpp"]];
} else {
    fileSource = [fileOriginal stringByAppendingString:[NSString stringWithFormat:@".%@", gFileExtension]];
}

代码工作正常。但是调试器在末尾显示垃圾NSString

在此处输入图像描述

如果我尝试添加retain到字符串,结果相同。到底发生了什么?

4

1 回答 1

1

Assuming your definition of gFileExtension is valid, why not try this:

NSString *fileSource;
if ([[fileOriginal pathExtension] length] > 0)
{
    fileSource = [[fileOriginal stringByDeletingPathExtension] stringByAppendingPathExtension:gFileExtension];
}
else
{
    fileSource = [fileOriginal stringByAppendingPathExtension:gFileExtension];
}

Using the path handling built into NSString, you don't have to worry about the dot; it's done for you.

于 2013-02-18T02:00:20.653 回答