0

I'm new to Objective-C and need help with the concept of pointers. I've written this code:

//myArray is of type NSMutableArray
NSString *objectFromArray = [myArray objectAtIndex:2];
[objectFromArray uppercaseString];

I assumed that this would change the string at myArray[2] since I got the actual pointer to it. Shouldn't any changes to the dereferenced pointer mean that the object in that location changes? Or does this have something to do with 'string immutability'? Either way, when I use NSLog and iterate through myArray, all the strings are still lowercase.

3
  • 2
    Ole gives you the answer you need. But some additional guidance for someone new to ObjC, I've found it doesn't pay to think of pointers to ObjC objects as pointers, per se. Just think of them as "objects" that you can "message" with objc bracket notation, dot notation, etc. If you try to do anything pointerish with them (like explicitly dereference, pointer arithmetic, etc), it's almost always the Wrong Way and often Bad Things will happen. Commented Sep 17, 2011 at 19:01
  • Thanks for the tip. I had a very basic idea of pointers before, but after learning ObjC, I feel like I've forgotten everything :D Commented Sep 17, 2011 at 19:10
  • Honestly, that's probably for the best ;-) Commented Sep 17, 2011 at 19:28

2 Answers 2

2

Shouldn't any changes to the dereferenced pointer mean that the object in that location changes?

Yes, they would. But if you read the documentation for uppercaseString, you see that it does not modify the string in place. Rather, it returns a new uppercase version of the original string. All methods on NSString work like that.

You would need an instance of NSMutableString to be able to modify its contents in place. But NSMutableString does not have a corresponding uppercase method, so you would have to write it yourself (as a category on NSMutableString).

Sign up to request clarification or add additional context in comments.

Comments

-1

of course!! no string in the array will be converted to uppercase as the statement [objectFromArray uppercaseString]; would have returned the uppercase string which was not collected in any object though. "uppercaseString" does not modify the string object itself with which is is called...!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.