Sami
Sami

Reputation: 1404

Objective-C [[NSXMLDocument alloc] initWithContentsOfURL:url options:0 error:&error]; help

I need a little help, i have a search field and button which trigger this method but i get the error underneath.

- (IBAction)fetchTracks:(id)sender {

NSString *input = [searchField stringValue];
NSString *searchString = [input stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"searchString: %@", searchString);

NSError *error;
NSString* libraryPath = [[NSString alloc] initWithString:@"~/Music/iTunes/iTunes Music Library.xml"];
NSURL *url = [NSURL URLWithString:libraryPath];

[doc release];
doc = [[NSXMLDocument alloc] initWithContentsOfURL:url options:0 error:&error];

NSLog(@"doc: %@", doc);

[itemNodes release];
itemNodes = [[doc nodesForXPath:@"ItemSearchResponse/Items/Item" error:&error] retain];

[tableView reloadData];
}

* -[NSXMLDocument initWithContentsOfURL:options:error:]: nil argument

Can anyone help, thanks, Sami.

Upvotes: 1

Views: 1647

Answers (3)

Abizern
Abizern

Reputation: 150755

I think you might need:

NSString *urlString = [@"~/Music/iTunes/iTunes Music Library.xml" stringByExpandingTildeInPath];
NSString* libraryPath = [[NSString alloc] initWithString:urlString];

Upvotes: 0

Nikita Rybak
Nikita Rybak

Reputation: 68046

You need to escape spaces in your code. E.g., like this

  libraryPath = [libraryPath stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

When I add this, your code doesn't crash.
But generally, I would recommend accessing files as files (e.g. NSString stringWithContentsOfFile). It will make your life easier.

You can see the list of characters URL can't contain here:

Unsafe:

Characters can be unsafe for a number of reasons. The space character is unsafe because significant spaces may disappear and insignificant spaces may be introduced when URLs are transcribed or typeset or subjected to the treatment of word-processing programs.

Upvotes: 1

theChrisKent
theChrisKent

Reputation: 15099

Change this line:

NSError *error;

To this:

NSError *error = nil;

Read this question for additional detail as to why this works: NSError: Does using nil to detect Error actually turn off error reporting?


However, you don't seem to care about the error object at all so you would be better off just calling these methods like this (replace &error with NULL)

doc = [[NSXMLDocument alloc] initWithContentsOfURL:url options:0 error:NULL];
...
itemNodes = [[doc nodesForXPath:@"ItemSearchResponse/Items/Item" error:NULL] retain];

Upvotes: 1

Related Questions