我想做的是设置一系列可以通过实例变量访问的 AVPlayer。一切都存储在 Realm 中,我在之前的 View 中用所有 Realm 变量实例化了 Collection。加载 View 后,我想加载所有播放器,然后使用来自位置的一些参数触发它们。问题是,当 locationManager
被调用时,播放器会在 Player 实例上返回 nil
。
我猜这是因为 locationManager
在单独的线程上被调用?如果是这种情况,确保玩家已被实例化的线程安全方法是什么?
这是带有 locationManager
和加载器的 View
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
不会保留这些属性。根据this关于被忽略的属性的 GitHub 问题,您遇到的是预期的行为。
来自链接的问题:
"Ignored properties are only guaranteed to be consistent across individual Swift instances, but retrieving an object from a collection creates a new Swift instance each time, thus the behavior that you see."
这意味着 locationManager(didUpdateLocations:)
中的 self.collection.players[i]
实际上是同一个 Realm
的新 Swift 实例您在 loadPlayers()
中创建的 code> 对象,这不是普通 Realm
属性的问题,因为它们是从 Realm
数据库中获取的,但是会导致忽略属性的问题,因为它们链接到特定的 Swift
实例并且只存在于内存中。因此,当您从集合中检索特定对象时(Player
实例来自“List”),所有被忽略的属性都会丢失。
总而言之,您将无法在集合中使用被忽略的 Realm
属性。
关于ios - 实例化可选 Realm 对象的线程安全方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45331474/