views:

60

answers:

2

I could not really find this in the documentation ...

I'm writing some unit tests and one of the tests that is supposed to fail is [NSURL URLWithString: @"cow"]. Because cow is not a valid URL.

However, it is happily parsed by NSURL with no errors at all. It does not return nil and it does not throw an exception. Calling [url absoluteString] on it turns it back into @"cow".

What is going on here? Is NSURL really supposed to allow this?

A: 

From the documentation for +URLWithString:

The string with which to initialize the NSURL object. Must conform to RFC 2396. This method parses URLString according to RFCs 1738 and 1808. ... If the string was malformed, returns nil.

Not being intimately familiar with RFC 2396, I can't say for certain, but I think you must have a minimum of a protocol and a host (even if the domain itself forwards to a host). I'd certainly expect nil.

If you're not getting "nil" back by passing @"cow", you should file a bug at bugreporter.apple.com. You may want to title it, "Don't Have a Cow."

Joshua Nozzi
Correct. The base rule is specified in “3. URI Syntactic Components” as `<scheme>:<scheme-specific-part>`. “c:w” would match that, “cow” does not.
Ahruman
As I noted in a comment on my answer, Ahruman is mistaken in taking this as the mandatory form a URL must take to be parsed. Relative URLs are valid and allowed.
Chuck
+3  A: 

NSURL allows relative URLs, which would include "cow".

The general form of a URI given in RFC 2396 allows relative references:

URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
relativeURI   = ( net_path | abs_path | rel_path ) [ "?" query ]
rel_path      = rel_segment [ abs_path ]
rel_segment   = 1*( unreserved | escaped |
                      ";" | "@" | "&" | "=" | "+" | "$" | "," )

Unless I'm misreading horribly, this means any sequence of valid characters can form a valid relative URL.

Chuck
Yes, but not through `+URLWithString:`.
Ahruman
The documentation says the URL is parsed according to RFC 1808 — a document titled "Relative Uniform Resource Locators," which allows relative or absolute URLs. See page 3 of that RFC, or pages 14-16 of 2396 for the the same definition. Relative URLs are allowed.
Chuck
Withdrawing my previous comment, replacing it with this: An obvious example I overlooked is href="/someotherdocument" used from within an existing hypertext document. I suppose it's up to the developer to maintain the context if relative URLs are given.
Joshua Nozzi
@Joshua Nozzi: Yep, the RFC actually says both that and what was in your deleted comment — "It must be emphasized that relative URI cannot be used reliably in situations where the document's base URI is not well-defined."
Chuck