Luke
Luke

Reputation: 9700

NSURL is being nulled when I try to set it to an NSString

I'm using the following code to load some sounds depending on which button a user clicked. The file path is loaded into testString perfectly, but when NSLogging URLToBeReturned, it comes out as (null). I'm not sure why it's not transferring over.

NSString *testString = [NSString stringWithString:[[NSBundle mainBundle] pathForResource:noteName ofType:@"m4a"]];
NSURL *URLToBeReturned = [NSURL URLWithString:testString];
return URLToBeReturned;

Upvotes: 0

Views: 166

Answers (2)

sergio
sergio

Reputation: 69047

Possibly because it was malformed (from NSURL reference) as a URL:

+ (id)URLWithString:(NSString *)URLString

Return Value

An NSURL object initialized with URLString. If the string was malformed, returns nil.

As to a fix (from the same reference):

URLString

The string with which to initialize the NSURL object. Must be a URL that conforms to RFC 2396. This method parses URLString according to RFCs 1738 and 1808. (To create NSURL objects for file system paths, use fileURLWithPath:isDirectory: instead.)

So, you can try using fileURLWithPath:isDirectory:

Upvotes: 0

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

Instead of

NSURL *URLToBeReturned = [NSURL URLWithString:testString];

use

NSURL *URLToBeReturned = [NSURL fileURLWithPath:testString];

Upvotes: 5

Related Questions