Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
April 22, 2018, 09:21:42 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
 
   Home   Help Search Login Register Chat  
Pages: [1]   Go Down
  Print  
Author Topic: Immutable NSString objects  (Read 1995 times)
enigmakv
Newbie
*
Posts: 37



« on: October 11, 2009, 12:12:09 AM »

Steve,

In class on Oct. 6th you discuss how the POINTER str2 can be changed to point to a different location in memory.  So if...
Code: (Objective-C)
NSString *str1 = @"This is string A";
NSString *str2 = @"This is string B";
...sets str2 to point to an immutable object containing "This is string B" what happens to that object/memory when the pointer str2 is changed to point to an immutable object containing the string "This is stringAThis is string B"?

Is that what you mean by the automatic autorelease of the Foundation objects?
Logged
skochan
Administrator
Hero Member
*****
Posts: 3114



« Reply #1 on: October 11, 2009, 09:40:57 AM »

The constant string objects @"..." are allocated by the compiler and they never get released (they have meaningless reference counts as you'll learn in Chapter 18.)

Cheers,

Steve Kochan
« Last Edit: October 12, 2009, 01:16:34 PM by skochan » Logged
Horst
Newbie
*
Posts: 3


« Reply #2 on: October 12, 2009, 12:37:09 PM »

I really have a problem in understanding the basic concept of immutable objects.

        NSString *str1 = @"This is string A";
   NSString *res = @"this is the res string";
   
   res= [NSString stringWithString:str1];
   
   NSLog(@"String str1:%@", str1);              this will print: String str1:This is string A
   NSLog(@"String res :%@", res);                this will print: String res :This is string A

I define the res string but then I can change it with the line following after it. I would have expected an error because I modifiy a string I have defined previously?

TIA Horst
Logged
skochan
Administrator
Hero Member
*****
Posts: 3114



« Reply #3 on: October 12, 2009, 01:21:47 PM »

You're not modifying the contents of the string, only the reference (i.e., pointer) to the string object.  In your example, res is set pointing two two different string objects.  The actual characters in either string cannot be changed, but res can be set to point to either one.

You may want to look at the stickied topic for Program 7.5/7.6 in this forum, which goes into the concepts of the difference between an object and the pointer to that object.

Cheers,

Steve Kochan
Logged
Horst
Newbie
*
Posts: 3


« Reply #4 on: October 13, 2009, 11:41:21 AM »

thanks, got it (I think...)
Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents ゥ 2009 classroomM.com. All rights reserved.