copy an object in objective-c [duplicate]
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:[so开发者_C百科urceCoverFlow 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
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
精彩评论