我无法为作为参数发送给方法的对象设置新值。看起来像这样:

- (void)updatePlayerWithOldSong:(id<ISong>)song
                     withNewSong:(id<ISong>)newSong{

    song = newSong; // -> here I want to change real object sent as parameter - in this case _chosenSong
    // more stuff here
}

当我调用时:
[self updatePlayerWithOldSong:_chosenSong withNewSong:newSong];

它没有按我的预期工作。 _chosenSong对象未更改。

最佳答案

那是因为您要做的就是互相复制对象引用:

- (void)updatePlayerWithOldSong:(id<ISong>)song
                     withNewSong:(id<ISong>)newSong{

    song = newSong;    // Has no effect
}

您可以传递一个指针到指针(id实际上是typedef'd指针),我猜:
- (void)updatePlayerWithOldSong:(id<ISong> *)song
                     withNewSong:(id<ISong>)newSong{
    NSAssert(song != NULL, @"Don't pass NULL");
    *song = newSong;
    // more stuff here
}

并像这样使用它:
[self updatePlayerWithOldSong:&_chosenSong withNewSong:newSong];

但是它似乎过于复杂。有什么问题:
_chosenSong = newSong;
[self updatePlayer];

或更妙的是,为chosenSong属性创建一个自定义setter方法,并调用[self updatePlayer]并简单地使用self.chosenSong = song;

09-18 20:40