简体   繁体   中英

Obj-C set value to real object sent as parameter

I cant set new value to object sent as parameter to method. It looks like this:

- (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
}

and when I invoke:

[self updatePlayerWithOldSong:_chosenSong withNewSong:newSong];

Its not working as I expected. _chosenSong object isn't changed.

That's because all you are doing is copying the object references over each other:

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

    song = newSong;    // Has no effect
}

You could pass a pointer-to-pointer ( id is actually a typedef 'd pointer) I guess:

- (void)updatePlayerWithOldSong:(id<ISong> *)song
                     withNewSong:(id<ISong>)newSong{
    NSAssert(song != NULL, @"Don't pass NULL");
    *song = newSong;
    // more stuff here
}

and use it like this:

[self updatePlayerWithOldSong:&_chosenSong withNewSong:newSong];

It seems overly-complicated though; what's wrong with:

_chosenSong = newSong;
[self updatePlayer];

or better still, create a custom setter method for the chosenSong property and have that call [self updatePlayer] and simply use self.chosenSong = song; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM