I know I should know this by now but I am not :frowning:

NSURL *url = [NSURL URLWithString:@""];

to my understanding, NSURL is the class and *url is the pointer, where is the alloc and init??

shouldn’t this code be link this

NSURL *url =[[NSURL alloc]init];
url = [NSURL URLWithString:@""]

I feel its a really stupid question but I want to make sure I understand what I am typing.


You need alloc + init when you are creating an object and then defining its characteristics by calling methods on that object (sometimes by way of a special init function, sometimes via other messages after init).

In this case, you are asking the class to create an object for you with those characteristics. The class may use alloc/init or may not, but that’s not your concern. You are not responsible for the memory or the configuration mechanism.

It may be easier if you break alloc and init onto different lines and think about it that way. The below pieces of code are, as best as I can tell from the documentation, equivalent.

Method 1, you are taking responsibility for all details of object creation

NSURL *url = [NSURL alloc]; // Ask the class for space
[url initWithString:@""]; // Ask the object to initialize itself. This is just a more sophisticated form of init

Method 2, you are asking NSURL to do all the nitty gritty details for you

NSURL *url = [NSURL URLWithString:@""]; // Ask the class to create and initialize an object with your URL

Note that with this particular class, there is no way to define a URL after the object is initialized, so you can’t do what we ordinarily think of:
Method 3, variation on method 1 that we usually use, doesn’t work with NSURL

NSURL *url = [NSURL alloc]; // Ask the class for space
[url init]; // Ordinarily we combine this on the previous line, but this way is more explicit
[url setURL:@""]; // Illegal, I believe