<p>In an application that I'm writing I have some code like this:</p>

<pre><code>NSWorkspace* ws = [NSWorkspace sharedWorkspace];
NSString* myurl = @"http://www.somewebsite.com/method?a=%d";

NSURL* url = [NSURL URLWithString:myurl];

[ws openURL:url];
</code></pre>

<p>The main difference being that <em>myurl</em> comes from somewhere outside my control. Note the %d in the URL which isn't entirely correct and means that URLWithString fails, returning <em>nil</em>.</p>

<p>What is the "correct" way of handling this? Do I need to parse the string and properly encode the arguments? Or is there some clever method in Cocoa that does all the hard work for me?</p>

I think the behaviour here is correct, because %d is not a valid component of a URL (% is the escape, but expects two hex characters to follow it).
You can't just URL encode the URL as given to you, because that would encode the /s and ?s as well, which you don't want.
So, the question is, what's the correct behaviour here?
Perhaps you would want it to be turned into...
```
```
http://www.somewebsite.com/method?a=%25d
```
```
(i.e. the % is encode to the encoded version of % in a URL, so when method gets the input, it sees a as being set to %d)
I don't think there's any library function which will do that sort of thing for you, since there's no 'correct' way to do it. About he only correct thing you can do is return an error message saying the URL you were given is invalid (just as URLWithString is)
If you wanted to try to handle the input, I guess you would need to search the URL for any % symbols which are not immediately followed by two hex characters, and then replace the % with %25 in that case. That should be quite possible with a regular expression, though I suspect there may be some additional complexities if your URLs start containing encoded versions of characters outside the ASCII character set.