我正在开发一个应用程序和一个小部件,该小部件需要从应用程序获取数据。我使用以下代码在NSUserDefaults上进行读写。而且我还使用$(PRODUCT_BUNDLE_IDENTIFIER).widget了小部件并$(PRODUCT_BUNDLE_IDENTIFIER)引用了这篇文章。但是小部件无法从应用程序或NSUserDefaults获取数据。我该如何运作?
$(PRODUCT_BUNDLE_IDENTIFIER).widget
$(PRODUCT_BUNDLE_IDENTIFIER)
func addTask(name: String?) { let key = "keyString" tasks.append(name!) let defaults = NSUserDefaults(suiteName: "group.Mins") defaults?.setObject(tasks, forKey: key) defaults?.synchronize() }
///////
let defaults = NSUserDefaults(suiteName: "group.Mins") let key = "keyString" if let testArray : AnyObject = defaults?.objectForKey(key) { let readArray : [String] = testArray as! [String] timeTable = readArray timeTable = timeTable.sort(<) print("GOT IT") print("timetable: \(timeTable)") }
要从同一组NSUserDefaults中读取和保存,需要执行以下操作:
写入您的NSUserDefaults:
// In this example I´m setting FirstLaunch value to true NSUserDefaults(suiteName: "group.myapp.test")!.setBool(true, forKey: "FirstLaunch")
从NSUserDefaults读取:
// Getting the value from FirstLaunch let firstLaunch = NSUserDefaults(suiteName: "group.myapp.test")!.boolForKey("FirstLaunch") if !firstLaunch { ... }
UserDefaults(suiteName: "group.myapp.test")!.set(true, forKey: "FirstLaunch")
UserDefaults(suiteName: "group.myapp.test")!.bool(forKey: "FirstLaunch")