how do you swap two arrays in obj-c
Is this a convenient way for swapping two ivar arrays in objective C?
- (void) foo {
NSArray *aux;
aux = array1;
array2 = array1;
array1 = array2;
}
Are there any alternatives? May it have problems related to retainCount under some circumstances? I am confused because in the program tha开发者_开发知识库t I am reviewing the swap is done by:
- (void) foo {
NSArray *aux;
aux = array1;
[aux retain];
array2 = array1;
array1 = array2;
[aux release];
}
Neither of them will work, you are not using your aux variable anywhere, at the end they will both point to the same memory location do this instead:
- (void) foo {
NSArray *aux;
aux = array1;
array1 = array2;
array2 = aux;
}
In your example, you're swapping just the pointers. And by the way, you're doing it wrong:
- (void) foo {
NSArray *aux;
aux = array1; /* aux is array1 */
array2 = array1; /* array2 is array1 */
array1 = array2; /* array1 is array1 */
}
If you have properties on those arrays, I'd recommend going with it:
- (void)swapMyArrays
{
NSArray *temp = [NSArray arrayWithArray:self.array1];
[self setArray2:array1];
[self setArray1:temp];
}
I think you have a mistake at the end, and it should be:
- (void) foo {
NSArray *aux;
aux = array1;
array1 = array2;
array2 = aux; // instead of array2 = array1
}
otherwise you make both arrays the same one.
I edited the answer as for the (correct) comments regarding a mistake in the variables I made.
精彩评论