【发布时间】:2025-11-27 21:40:01
【问题描述】:
我正在为 iOS 编写一个小型通用游戏。 高分将通过 iCloud 键/值存储在设备间同步。
获取最新分数:
func retrieveHighestScore() -> Int64 {
let iCloudScore: Int64 = NSUbiquitousKeyValueStore.defaultStore().longLongForKey(KeyValueKeyClassification.KeyHighscore.toRaw())
let localScore: Int64 = Int64(NSUserDefaults.standardUserDefaults().integerForKey(KeyValueKeyClassification.KeyHighscore.toRaw()))
var result: Int64 = 0
if localScore > iCloudScore {
storeNewHighscore(localScore)
result = localScore
} else {
storeNewHighscore(iCloudScore)
result = iCloudScore
}
return result
}
存储新的高分
func storeNewHighscore(newScore: Int64) {
NSUbiquitousKeyValueStore.defaultStore().setLongLong(newScore, forKey: KeyValueKeyClassification.KeyHighscore.toRaw())
NSUserDefaults.standardUserDefaults().setInteger(Int(newScore), forKey: KeyValueKeyClassification.KeyHighscore.toRaw())
if NSUbiquitousKeyValueStore.defaultStore().synchronize() {
println("Synched Successfully")
}
}
由于某种原因,分数没有同步。
- 没有错误
- 没有崩溃
- 没有空值
我总是从当前设备上获得最高分,而不是其他设备上的最高分。
原因可能是在 itunesconnect 中,还是我的代码有问题?我正在使用 ipad 和 iphone 进行测试,都登录到我自己的 icloud 帐户。
我正在注册这样的更改:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "icloudKeyValueChanged", name: NSUbiquitousKeyValueStoreDidChangeExternallyNotification, object: nil)
if NSUbiquitousKeyValueStore.defaultStore().synchronize() {
println("initial Synched Successfully")
}
return true
}
但从未调用过函数“icloudKeyValueChanged”。
iCloud 功能一切正常:
【问题讨论】:
-
我相信 iCloud 存储需要 plist-objects(?) 您可能需要将其中一些 Ints 包装在 NSNumber 中...
-
@nickfalk 我很确定这不是问题所在。否则像“setlonglong”这样的伤口不存在
-
好的,我遇到了与
Swift+NSUserDefaults非常相似的问题,除了没有报告错误之外,使用 Ints 不会凝胶化。 -
你解决了吗?
标签: ios xcode swift ios8 icloud