objective c NSURL may not respond to +initFileURLWithPath
I have two lines of code in the applicationDidFinishLaunching function:
NSString *targetFilePath = @"/Users/bob/Documents/About_Stacks.pdf";
NSURL *targetFileURL = [NSURL initFileURLWithPath:targetFilePath];
and I am getting the warning (title) in the second line...
I have no idea what I am doing wrong. This is an absurdly simply application... I have read other posts about reordering methods, but I am using classes provided by NS, nothing of my own.
Any adv开发者_高级运维ice would be much appreciated.
Thanks.
initFileURLWithPath:
is an instance method, not a class method, so you have to create an instance of the class first with alloc
. So:
NSString* targetFilePath = @"/Users/bob/Documents/About_Stacks.pdf";
NSURL* targetFileURL = [[NSURL alloc] initFileURLWithPath:targetFilePath];
If you want to use the convenience method, use fileURLWithPath:
, so:
NSURL* targetFileURL = [NSURL fileURLWithPath:targetFilePath];
You have to alloc
an NSURL
first.
NSURL *targetFileURL = [[NSURL alloc] initFileURLWithPath:targetFilePath];
If the method starts with "init", it means it should be called on an allocated instance, not on the class itself.
The warning is normal as the method initFileURLWithPath
is an instance method and not a class method. The proper way to use it is:
NSString *targetFilePath = @"/Users/bob/Documents/About_Stacks.pdf";
NSURL *targetFileURL = [[NSURL alloc] initFileURLWithPath:targetFilePath];
I think the problem is the NSURL has to created first using alloc . Just declaring it will not work.
Also I think you will need to release it later, otherwise there will be a potential leak.
NSURL *targetFileURL = [[NSURL alloc] initFileURLWithPath:targetFilePath];
//do some stuff
[targetFileURL release ];
精彩评论