Is this a convenient way for swapping two ivar arrays in objective C?
在objective C中交换两个ivar数组是否方便?
- (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 that I am reviewing the swap is done by:
有什么选择吗?在某些情况下,会不会有与遗产计算有关的问题?我很困惑,因为在我正在审查的项目中,是由:
- (void) foo {
NSArray *aux;
aux = array1;
[aux retain];
array2 = array1;
array1 = array2;
[aux release];
}
3 个解决方案
#1
2
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];
}
#2
3
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;
}
#3
1
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.
我编辑了关于我所犯的变量错误的(正确的)评论的答案。
#1
2
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];
}
#2
3
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;
}
#3
1
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.
我编辑了关于我所犯的变量错误的(正确的)评论的答案。