1

Possible Duplicate:
How to copy an object in objective c

I have a very basic question. I would like to copy an object. So duplicate it.

It is like:

    ProductEntity *pCopy = [[ProductEntity alloc]init];
    ProductEntity *pTemp = [[ProductEntity alloc]init];
    pCopy = [sourceArray objectAtIndex:[sourceCoverFlow selectedCoverIndex]];
    [pTemp setBalance:pCopy.balance];
    [pTemp setAvailableBalance:pCopy.availableBalance];
    [pTemp setProductType:pCopy.productType];
    [pTemp setProductTypeDesc:pCopy.productTypeDesc];
    [pTemp setIsCorpAccount:pCopy.isCorpAccount];
    [pTemp setIndex:pCopy.index];
    [pTemp setAlias:pCopy.alias];
    [pTemp setSaveAccount:pCopy.saveAccount];
    [pTemp setAccount:pCopy.account];

So, pTemp is a new Object which is a copy of pCopy?

if I modify something of pTemp, will pCopy be modified?

Thnks

Community
  • 1
  • 1
ValentiGoClimb
  • 750
  • 3
  • 13
  • 23
  • 1
    My, @ValentiGoClimb has a reputation of 26 and is deemed evil already? That seems a bit harsh. Besides, worse happens here on StackOverflow. I just had someone with a far higher reputation implement my answer but accept someone else's because it involved cool custom frameworks. – Elise van Looij Jul 04 '11 at 16:10
  • I was going more on the fact that he has been around for almost two months and has several asked questions. *shrug* – James Sumners Jul 04 '11 at 17:50

1 Answers1

3

pTemp is a new object whose properties contain values that are either copies of pCopy's properties in the case of scalar property types or references in the case of object property types. In Objective-C, the default for objects is by reference. In Cocoa, you can make a copy of an object that implements the NSCopying protocol using the copy selector. If ProductEntity conforms to the NSCopying protocol, then this code could be valid:

ProductEntity *pCopy = [[sourceArray objectAtIndex:2] copy]; 

To make a subclass of NSObject conform to the NSCopying protocol, you need to implement copyWithZone:, see NSCopying Protocol

Quuxplusone
  • 23,928
  • 8
  • 94
  • 159
Elise van Looij
  • 4,162
  • 3
  • 29
  • 52
  • Elise's original answer included reference to the `bycopy` modifier, implying that a parameter declared as `(bycopy ProductEntity *)productEntity` would be copied by automagic invocation of its `copy` method. This is sort-of true when you're talking about remote messaging (messaging between different address spaces), but it's false in general. Adding the `bycopy` modifier to a normal single-address-spaced Objective-C program won't change its semantics at all. – Quuxplusone Jan 10 '13 at 19:57
  • Hmm, yeah, that's what happens when one talks about modifiers one practically never uses. Ta, @Quuxplusone. – Elise van Looij Jan 12 '13 at 21:00