ios - 将对象的Obj-C设置值作为参数发送

标签 ios objective-c pointers reference

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

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

关于ios - 将对象的Obj-C设置值作为参数发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35460272/

相关文章:

c# - 是否可以将大的本地化字符串换成他们自己的文件?

ios - 如何让音乐在所有 View 中继续播放

iphone - 使用 Telerik TestStudio 和 Jenkins 的连续 iPhone 集成测试服务器

iphone - Objective-C 和 iOS 中的超全局变量

c++ - 编写跨平台代码时使用 char* 而不是 void* 有什么陷阱吗?

ios - Swift 分派(dispatch)到子类扩展中的重写方法

ios - 如何循环 NSString N 次?

iphone - 访问 iPhone 用户歌曲和视频?

c++ - 将指向成员函数的指针转换为 intptr_t

c - 字符串指针数组的大小?