我有以下问题,因为我刚刚开始编写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 指针
提前致谢。