views:

693

answers:

1

Hi, I'm trying to make an object in one array equal to another. If I set each property individually, it works fine, but I want to set one object equal to antoher without writing a function to run through each property.

-(void)DrawCard: (int) wp{
[self GetNc :(wp)];
if (nc > 0){ 
 ((card*) [[Hands objectAtIndex:wp] objectAtIndex:nc]) = ((card*) [[Draws objectAtIndex:wp] objectAtIndex:0])
}

}

(wp stands for which player. All GetNc does it set the integer nc (for new card), by finding the highest index of a card object currently being used in Hands).

That won't compile, but setting an individual property does:

 ((card*) [[Hands objectAtIndex:wp] objectAtIndex:nc]).suit = ((card*) [[Draws objectAtIndex:wp] objectAtIndex:0]).suit;

And trying without casting gives invalid l-value error as well ie:

     [[Hands objectAtIndex:wp] objectAtIndex:nc] = [[Draws objectAtIndex:wp] objectAtIndex:0];

(Is it ever possible to set an array object without casting?)

I appreciate your time to read and respond. Cheers!

+2  A: 

This will set that index of the array to point to the same object. I hope you understand that this does not copy the object.

[[Hands objectAtIndex:wp] replaceObjectAtIndex:nc withObject:[[Draws objectAtIndex:wp] objectAtIndex:0]];
newacct
So if the object in Draws changes, both Hands and Draws will return the new Draws value? Thanks.. how can I copy the object so I can adjust them independently?
If the object supports copying, then you can use the "copy" method to copy it.
newacct
Can you give an example? The objects in question are a card class I wrote. How do I make them support copying?
Are you sure you need to copy it? (If your card objects themselves are immutable then you don't need to copy it.) Anyway, to support copying, you implement the "copyWithZone:" method. Here is one that will perform shallow copying:- (id)copyWithZone:(NSZone *)zone { return NSCopyObject(self, 0, zone);}
newacct