gpt4 book ai didi

swift - NSUserDefaults 未加载 Today Extension (Swift)

转载 作者:可可西里 更新时间:2023-11-01 02:17:19 25 4
gpt4 key购买 nike

我正在尝试制作一个 Today Extension,在主应用程序中,favorite 正在从 arar2 中正确写入和读取>。 favorite 是类 Book 的属性。但是,当我尝试从 Today Extension 访问所有 Book 对象的数组的 favorite 属性时,arar2 是空的。

主要应用:

var favorite: Bool {
get {
let ar = NSUserDefaults.standardUserDefaults().stringArrayForKey("favorites") ?? []
let ar2 = NSUserDefaults(suiteName: "group.com.TodayExtension")
ar2?.synchronize()
let tempVar = ar2?.stringArrayForKey("favorites") ?? []
print("ar1: \(ar)")
print("tempVar: \(tempVar)")
return ar.contains {
$0 == slug
}
}

set {
var ar = NSUserDefaults.standardUserDefaults().stringArrayForKey("favorites") ?? []
let ar2 = NSUserDefaults(suiteName: "group.com.TodayExtension")
let contains = self.favorite
if (newValue && !contains) {
ar.append(self.slug)
ar2?.setObject(ar, forKey: "favorites")
ar2?.synchronize()
} else if (!newValue && contains) {
let idx = ar.indexOf {
$0 == slug
}

if let idx = idx {
ar.removeAtIndex(idx)
}
}

NSUserDefaults.standardUserDefaults().setObject(ar, forKey: "favorites");
}
}

输出:

ar1: ["Harry Potter", "Compound", "Nefarious"]
tempVar: ["Harry Potter", "Compound", "Nefarious"]

今日延期:

func loadData(force: Bool, completion:(() -> Void)?) {
DATA.fetchEateries(force) { (error) -> (Void) in
dispatch_async(dispatch_get_main_queue(), {() -> Void in
if let completionBlock = completion {
completionBlock()
}

self.books = self.DATA.books

if self.books != [] {
for book in self.books {
if book.favorite {
print("I like it!")
} else {
print("I don't like \(book.name)")
}
}
}
else {
print("there are no books")
}
})
}
}

输出:

ar1: []
tempVar: []
I don't like Harry Potter
ar1: []
tempVar: []
I don't like Compound
ar1: []
tempVar: []
I don't like Nefarious

最佳答案

standardUserDefaults 不会为两个目标返回相同的用户默认值。您必须创建应用程序组,然后使用 NSUserDefaults(suiteName: "group")

关于swift - NSUserDefaults 未加载 Today Extension (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36119048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com