PDA

View Full Version : Objective-C/Xcode question on pointers and variables




Sandy Santra
Apr 15, 2009, 12:06 PM
My study guide says:

It is possible to declare and initialize the pointer variable for a string in one go:

NSString *favoriteActress = @"Julia";

No problem. I (sort of) understand that.

Then it says: "Once you have initialized the variable, i.e. favoriteComputer, you may give the variable another value, but you cannot change the string itself" and gives the following code:

#import <foundation/foundation.h>
int main (int argc, const char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *favoriteComputer;
favoriteComputer = @"iBook";
favoriteComputer = @"MacBook Pro";
NSLog(@"%@", favoriteComputer);
[pool release];
return 0;
}

This is sort of confusing for two reasons:

(1) Is the second line "favoriteComputer = @"MacBook Pro";" the "giving the variable another value" that the book mentions? I get the impression that when you give it another variable like that, it wipes away the first variable given, right?

(2) What does the book mean by "you cannot change the string itself"? Very confused on this one. favoriteComputer is a variable of type "pointer" that points to an address. iBook and MacBook Pro are values that it took (except that doesn't make sense, unless those two things are themselves variables defined somewhere else). What am I missing here?

Any explanation(s) greatly appreciated! Thanks..



scottb99
Apr 15, 2009, 12:25 PM
First, in C, this would be:
char *mychars = "test string";

and the variable is just a pointer, and it points to a string constant.
In that case it may be bad to change/can not change.

In your case though, you may want to look at NSMutableString.

Scott Becker

lee1210
Apr 15, 2009, 01:03 PM
A variable holds a value. In the case of primitives like int, this value stores a number. In the case of a pointer (indicated with a *), the value that is stored is a memory address where some data is stored. In Objective-C, all objects are referenced in this manner, so you always have a pointer to the object.

In this case, the value stored in favoriteComputer is a pointer to an NSString object. The value of the pointer is changed from the original memory where the NSString literal @"iBook" is stored to point instead to the memory where the NSString literal @"Macbook Pro" is stored. The only memory associated with favoriteComputer is the space needed to store a memory address. This is being changed.

Regarding not being able to change the string itself, that just means you can't change the value in the memory pointed to. Since NSString is unmutable, this isn't really an option anyway.

-Lee