Shallow copy or Deep Copy with NSValue

This is very important issue in memory management in Cocoa. About 10 years ago, I didn’t worry about this issue much, because at that time things were clear and API were not that complicated. However, it is not true any more. Due to performance issues, copying memory is avoided if possible, and in that case shallow copy is prefered. ( Nowadays, even weak reference or strong reference should be considered also. )

Collections in Cocoa are usually shallow-copy-based, if a programmers want it in the other way. Apple prepares deep copy option for those users.

Then, how about NSValue and NSNumber? Recently I started using these two classes heavily. They are used to make opaque types like int, float, or other C structures work with the Cocoa collections. Any objects based on NSObject can be put into collections. However the primitive types can’t be. So, they should be wrapped in NSValue and NSNumber. How to do so is shown below.

typedef struct complexTypeConveyer
	int dataSize;
	int year;
	int tag;
} complexTypeConveyer;

// Move to the conveyer
complexTypeConveyer *theConveyer = (complexTypeConveyer *)malloc(sizeof(complexTypeConveyer));;
	theConveyer->dataSize = dataSet.dataSize;
	theConveyer->year = dataSet.year;
	theConveyer->tag = dataSet.tag;

NSValue *aValue = [NSValue valueWithBytes:theConveyer objCType:@encode(complexTypeConveyer)];

The [NSValue valueWithBytes: objCType:] is a kind of a convenience method. You don’t need to wrap each data member of a given data structure.
I will post a separate article on this, because it has some issues with pointers pointing to other structures.

Then, how will the data be kept? It is self-contained, or in other words, the data, theConveyer holds, are deep-copied shallow-copied. But Apple’s document doesn’t clearly mention it. So, test it for yourself and check if things work as you want.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: