我有以下問題,因爲我剛開始編碼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:IM使用ARC
編輯
我真的想完成,會是這樣的:
_second = _first
MySecondClass *tmp = [[MySecondClass alloc] init];
_first = &tmp;
但是這表明編譯器錯誤:隱將間接指針轉換爲指向「MySecondClass *」的Objective-C指針不允許使用ARC
在此先感謝。
拋出什麼樣的異常?控制檯應該顯示。 –
例外: 未捕獲的異常: - [MySecondClass copyWithZone:]:無法識別的選擇器發送到實例0xf305570 我不想複製內存,只是指向它的指針。 _first指針應該指向一個新的對象。 – Dom
我總是遇到這種問題,最後我寫了copyWithZone。有一種叫做deepcopy和shallowcopy的背後原因。 –