0
votes

Hey guys I just have a simple objective c question, I have been looking over my companies code base and I have stumbled upon something interesting. When should you use [[alloc] init] and when should you not. Here is a classic example:

Case 1:

NSString *url = nil;
url = @"hi";

Case 2:

NSString *url = [[NSString alloc] init];
url = @"hi";

So when should you use Case 1 and when should you use Case 2? I am hoping someone can settle this for me once and for all, throughout my app development I have been using Case 2 because I thought it was equivalent to calling a "new" in C++ (basically invoking an objects constructor). I am shocked that Case 1 even works, because Case 1 indicates no invokation of a constructor or memory allocation for that object. Case 1 is used everywhere in the code base I am looking at though.

3
Avoid applying C++ mechanics to Objective-C. ObjC offers no operator overloading unlike C++, so manipulation of Objc objects ( such as internal value assignment ) is always done via methods associated with that class, never the '=' operator.David Zech
Also instead of using [[... alloc] init] you could use [... new], it's the same, but in the first you can customizeaguilarpgc

3 Answers

2
votes

alloc creates storage and does some basic automatic setup, returning an instance of the class. init allows the instance to configure itself as per the logic required for that class. = assigns a different instance to the pointer.

So the first is always correct, the second always incorrect. There's no point creating an instance of an object then throwing it away one line later.

(aside: with ARC you can always skip the = nil as it's implied; in your case you could skip it regardless because of the following assignment)

2
votes

@"hi" creates an instance of NSString. It does the allocation and initialization. Therefore, in case 2, you are pointlessly allocating memory and then reassigning the "url" pointer to a new piece of memory.

You have to remember that "url" is a pointer. Just like in C or C++, when you use the "=" operator you are reassigning where it is pointing, you are not affecting the memory it used to be pointing at. In C, if you want to change the value stored at the newly allocated memory, you would have to use the dereference operator.

1
votes

alloc creates an object. So you use it when you want to create an instance of a class. In this case, you do not want to create an object, because you're going to assign the existing object @"hi" to the variable. So you would never write Case 2, as it creates an object and immediately discards it for another object.