文件名NSString在空间中添加不必要的%20

解决(感谢Regexident)

我有一个应用程序将PDF的文件path传递给一个自定义的-(id)init init方法。 它被添加到表中,当它被选中时,它调用一个不存在的文件的else语句:

 - (void) gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index { NSLog (@"Selected theArgument=%d\n", index); UIViewController *viewController = [[[UIViewController alloc]init]autorelease]; { //if file is built-in, read from the bundle if (index <= 3) { // first section is our build-in documents NSString *fileURLs = [_documentIconsURLs objectAtIndex:index]; NSLog(@"file url -%@", fileURLs); viewController = [[[xSheetMusicViewController alloc]initWithContentURL:fileURLs]autorelease]; } //if file is external, read from URL else { // second section is the contents of the Documents folder NSString *fileURL = [_documentIconsURLs objectAtIndex:index]; NSLog(@"file url -%@", fileURL); NSString *path; NSString *documentsDirectoryPath = [self applicationDocumentsDirectory]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); path = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileURL]; if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectoryPath]) { viewController = [[[xSheetMusicViewController alloc]initWithDocumentURL:fileURL]autorelease]; } else { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure!" message:@"The Selected File Does Not Exist" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alert show]; [alert release]; return; } } [self.navigationController setNavigationBarHidden:YES animated:NO]; [UIView beginAnimations:@"animation" context:nil]; [UIView setAnimationDuration:1]; [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.navigationController.view cache:YES]; [self.navigationController pushViewController:viewController animated:NO]; [UIView commitAnimations]; } } 

所以每当我有一个名字中没有空格的文档时,它就会被推入并进入。 但是当文件名有一个空格时,就表示不存在。 当我删除if-else方法时,它是init的,但是因为文件不存在而崩溃。 我尝试用常规空格replace文件path中的%20,但该方法继续调用else部分。

那么,文件path是不是标准化和可读性,或者是我的其他方法是错误的?

由于你的path似乎是一个百分比转义的pathstring,我会试试这个:

 [fileURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] 

我将fileURL重命名为fileURLString ,以明确它是一个包含URLpath的NSString,而不是一个实际的NSURL(你的variables名可能会错误地暗示)。

但我会检查填充_documentIconsURLs的代码,因为它可能是你的问题的起源。