0

我有以下问题,因为我刚刚开始编写objective-c。

我有一些例子

@interface MyClass
    @property (strong) MySecondClass *first;
    @property (strong) MySecondClass *second;
@end

@implementation MyClass
    @synthesize first = _first;
    @synthesize second = _second;

    /*this is called while initialisation*/
    -(void) initialisation{
        _first = [[MySecondClass alloc] init];
        _second = [[MySecondClass alloc] init];
     }

    /*what i want to do*/
    -(void) swap{
        // second one should be replaced with first one
        _second = _first; 

        // first pointer should be replaced by new instance
        _first = [[MySecondClass alloc] init];
    }

@end

问题是,当我调用交换方法时,_first 仍然指向旧对象,因此 _second 将被相同的新对象替换。

我已经尝试过如下复制,但它引发了异常。

 _second = [_first copy];

PS:我使用ARC

编辑

我真正想要完成的是:

 _second = _first
 MySecondClass *tmp = [[MySecondClass alloc] init];
 _first = &tmp;

但这显示了编译器错误:ARC 不允许将间接指针隐式转换为指向“MySecondClass *”的 Objective-C 指针

提前致谢。

4

2 回答 2

0

我的新答案:

您还应该确保您尝试复制的类实现了" NSCopying" 协议。例如,UIViewController 没有实现它,因此它不会响应对“复制”或“ copyWithZone”的调用。

尝试以不同于使用“ copy”的方式重置该指针。

我原来的答案:

尝试通过其访问器引用属性。

例如:

self.second = self.first;

self.first = [[MySecondClass alloc] init];

等等

唯一必须直接使用“ _second”&“ _first”的地方是类的 init 方法。

于 2012-11-24T15:11:12.473 回答
-1

我真正想要完成的是:

_second = _first
MySecondClass *tmp = [[MySecondClass alloc] init];
_first = &tmp;

但这显示了编译器错误:ARC 不允许将间接指针隐式转换为指向“MySecondClass *”的 Objective-C 指针

That's because the values of _first, _second, and tmp are already pointers, so “<code>&tmp” is a pointer to a pointer—an “indirect pointer” (not especially clear wording on the compiler authors' part).

The solution there is to not say &tmp. You just want tmp here.

于 2012-11-24T18:12:01.340 回答