Passing a string


#1

Besides the difference of writing code efficiently, what exactly is going on here?

Passing the literal syntax of NSString directly to NSMutableArray
[items addObject:@"One"]; [items addObject:@"two"]; [items addObject:@"three"];
vs.

Creating the NSString objects, then passing them to NSMutableArray
[code]
NSString *one = @“One”;
[mutableArray addObject:one];

NSString *two = @“two”;
[mutableArray addObject:two];

NSString *three = @“three”;
[mutableArray addObject:three];
[/code]


#2

I think (but am not 100% certain) that pointers to compile-time constant objects (e.g., @“One”) live on the heap.

The NSString pointers (e.g., one) will be pushed onto the stack when the enclosing method is invoked, and popped off when the method returns.

So the difference is a little more memory usage with explicit NSString declarations, but really, not enough to worry about. Use whichever method works best for you.

Just keep in mind that you don’t want to repeat yourself, e.g., by hard-coding @“One” in more than one place in the application. And if it has some kind of special meaning (like 2.718281828) then declare a read-only property telling what the darn thing is (like the base of the natural log) even if it’s used only once.


#3

Thanks, I got the idea. While we’re at it, I have another question if you don’t mind helping me out :open_mouth:

On page 48, it says - it’s a good practice to use accessor methods to access instance variables instead of passing the instance variables by name. Because:

I’m just trying to understand what he exactly means by “an accessor method may change something about the instance variable”.
So from what I understand, changing (2+2) to (4+4) from the code below could be an example of that. Yes?

- (void)setValue:(int)i
{
    _value = i + (2 + 2);
}

I appreciate your help.


#4

Given the context of the passage – a -description method in which the only accessors are getters – no, I do not believe that’s the kind of thing to which the authors are referring.

As a totally contrived example, perhaps a given variable should never be nil. The getter could check for that and force it to a default value. Or maybe it’s an array that’s accessed only rarely but takes some time to set up (again, a contrived example).

The point is that the getter may do something important. Rather than having to remember which getter is “special” – or worse, having to enhance the code to change an existing field so its getter does something special (and thus hoping you catch all the places the instance variable was used explicitly) – it’s easier and more reliable to just use the getter (and setter) for everything.


#5

Alright, thanks for the help :wink: