Noob: Copying Classes

Member
Posts: 153
Joined: 2004.12
Post: #1
If i do something like:

Code:
myClass *a;
myClass *b;

a = [[myClass alloc] init];
b = a;
[b doSomething];

Whatever it is i did with "b" happens to "a"...

Is there a way to copy "a" to "b" so that when i change "b", "a" doesnt also change?
in other words i want to make a unique copy of "a" (with its own memory) to "b".

There was a long silence...
'I claim them all,' said the Savage at last.
Quote this message in a reply
Member
Posts: 304
Joined: 2002.04
Post: #2
a and b are pointers. So you are setting them to point to the same object.

If you want a copy then make sure your class conforms to the NSCopying protocol and you implement the copyWithZone: method:

http://developer.apple.com/documentation...pying.html

Then read:

http://developer.apple.com/documentation.../10000011i

especially the “Implementing Object Copy” :

http://developer.apple.com/documentation...9/BBCEBJCH

also look up "NSCopyObject" here if you only want a "shallow" copy:

http://developer.apple.com/documentation...tions.html

hth,
Codemattic
Quote this message in a reply
Member
Posts: 153
Joined: 2004.12
Post: #3
Awesome, thanks a lot for the read.

Just for clarification: Is there a difference between creating a pointer to an object, and creating a shallow copy of an object?... They both 'point to' or reference the original memory.

There was a long silence...
'I claim them all,' said the Savage at last.
Quote this message in a reply
Member
Posts: 304
Joined: 2002.04
Post: #4
yes. Creating a shallow copy means that you get a new object - but all of its ivars objects are only pointers to the same ivars as the original. Creating a deep copy means that new ivars are created with the new object also. The difference between deep and shallow has to do with how the object's ivars are handled.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Copying Projects and Files mikey 4 2,516 Jul 28, 2009 10:42 AM
Last Post: AnotherJake
  C++ Interlocking Classes merrill541 1 2,580 Jan 25, 2009 08:43 PM
Last Post: akb825
  Noob: Accessing Structures from Cocoa Classes MikeC 15 7,209 Oct 19, 2007 02:42 PM
Last Post: MikeC
  Trouble With Template Classes in C++ Nick 4 3,158 Nov 21, 2006 10:25 AM
Last Post: DoG
  Trouble with template classes ermitgilsukaru 2 2,622 Aug 11, 2006 02:00 PM
Last Post: ermitgilsukaru