问题
SOLVED (Thanks Regexident)
I have an app that passes the file path of a PDF to a custom -(id)init
init method. It is added to the table and when it is selected, it calls the else statement for a non existent file:
- (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];
}
}
So whenever I have a document with no space in it's name, it pushes and inits. But when the file name has a space in it, it says it does not exist. And when I remove the if-else method, it init's, but crashes because the file doesn't exist. I've tried to replace the %20 in the file path with a regular space, but the method continues to call the else part.
So, is the file path not standardized and readable, or is my else method wrong?
回答1:
As your path appears to be a percentage escaped path string I'd try this:
[fileURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
And I'd rename fileURL
to fileURLString
to make clear that it's an NSString containing a URL path, not an actual NSURL (which your variable name would falsely imply).
But I'd check the code that populates _documentIconsURLs
, as it's probabaly the origin of your problem.
来源:https://stackoverflow.com/questions/8107303/file-name-nsstring-adds-unnecessary-20-in-space