【发布时间】:2017-07-26 15:33:48
【问题描述】:
我要做的是设置一系列可以通过实例变量访问的 AVPlayer。一切都存储在 Realm 中,我已经在上一个视图中使用所有 Realm 变量实例化了 Collection。视图加载后,我想加载所有播放器,然后使用位置中的一些参数触发它们。问题是,当 locationManager 被调用时,播放器会在 Player 实例上返回 nil。
我猜这是因为locationManager 在单独的线程上被调用?如果是这种情况,确保玩家已被实例化的线程安全方法是什么?
这是locationManager 和加载器的视图
class WalkMapViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {
/* …lots of outlets */
var collection:Collection!
override func viewDidLoad() {
/* …lots of other init stuff */
self.loadPlayers()
}
func loadPlayers() {
// get a url from somewhere
for (i,_) in self.collection.players.enumerated() {
// loop through the players and load them
self.collection.players[i].player = AVPlayer(url: url)
}
}
func locationManager(_ manager:CLLocationManager, didUpdateLocations locations:[CLLocation]) {
for (i, _) in self.collection.players.enumerated() {
self.collection.players[i].play()
}
}
}
这是一个大大缩短的 Collection 类,它是一个 Realm 对象,在 ignoreProperties 中有 players。
class Collection: Object, Mappable {
var players = List<Player>()
}
这是 Player 类,它也是一个嵌入在 Collection 中的 Realm 对象,并且在 ignoreProperties 中有player
class Player: Object, Mappable {
var player:AVPlayer?
}
【问题讨论】:
-
这很可能与线程无关,如果你试图从另一个线程访问
Realm对象,你会得到一个错误而不是一个 nil 对象。是这一行:self.collection.players[i].play()返回 nil 吗? -
是的@DávidPásztor,正确。在
loadPlayers()范围内可以访问播放器。 -
遗憾的是,这是预期的行为,正如我所怀疑的,它与线程无关,而是与被忽略的属性有关。请参阅下面的完整解释我的答案。