开发者

Delete characters in a string in Objective-C

I've an 开发者_开发百科NSOpenPanel called oPanel. From it, I get the path of a folder. As I use URLs (instead of the deprecated filenames) I want to get rid of the beginning (file://localhost).

But I have the following error that I can't understand:

2011-07-29 18:01:45.587 RedimV3[12857:407] -[NSURL length]: unrecognized selector sent to instance 0x1023543d0
2011-07-29 18:01:45.588 RedimV3[12857:407] -[NSURL length]: unrecognized selector sent to instance 0x1023543d0

Here is the code:

NSArray *files = [oPanel URLs];
NSLog(@"before: %@", [files objectAtIndex:0]);
NSMutableString *temp = [[NSMutableString alloc] initWithString:[files objectAtIndex:0]];
[temp deleteCharactersInRange:NSMakeRange(0,15)];
NSLog(@"after: %@",temp);

The first NSLog works, the second doesn't.

I will be glad if you can help me, thanks.


[files objectAtIndex:0] is probably an NSURL, not an NSString. Try using [[files objectAtIndex:0] path] instead. In fact, if you use -path you won't even have to worry about the file:// part.


If you just want the file name then you would do as @jtbandes said with a minor correction to use the lastPathComponent instance method of NSString

Quick and dirty version

NSArray *files = [oPanel URLs];        
NSLog(@"before %@",[files objectAtIndex:0]);
NSString *fileName = [[[files objectAtIndex:0] path] lastPathComponent];
NSLog(@"after :%@",fileName);

More readable code version

NSArray *files = [oPanel URLs];
NSURL *file = [files objectAtIndex:0];
NSLog(@"before %@",file);
NSString *localPath = [file path];
NSString *fileName = [localPath lastPathComponent];
NSLog(@"after :%@",fileName);


You need to turn the NSURL into a string...

NSURL *myURL = [files objectAtIndex:0];
NSMutableString *string = [NSMutableString stringWithString:[myURL absoluteString]];
[string deleteCharactersInRange:NSMakeRange(0,15)];
NSLog(@"after: %@", string);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜