參數(shù)和設(shè)置是變動較少的數(shù)值,可以用于配置應(yīng)用程序的行為或外觀。如果 WatchKit 應(yīng)用程序使用參數(shù)進(jìn)行配置,就可以在工程中添加一個 WatchKit 專用設(shè)置包來顯示這些設(shè)置。此設(shè)置包置于 iOS 應(yīng)用程序中,而設(shè)置本身會在用戶手機(jī)上顯示。
WatchKit 設(shè)置包與 iOS 設(shè)置工作包的工作流程相同。此設(shè)置包定義了系統(tǒng)控件和各控件修改的參數(shù)名稱。用戶手機(jī)的 Apple Watch 應(yīng)用程序會獲取設(shè)置包信息以便顯示實(shí)際控件。當(dāng)用戶更改控件數(shù)值時,系統(tǒng)會更新底層參數(shù)值。
如需獲取設(shè)置包工作的詳細(xì)信息,請參考 Preferences and Settings Programming Guide。
請按照以下操作向 Xcode 項(xiàng)目添加 WatchKit 設(shè)置包:
Settings-Watch.bundle 名稱來創(chuàng)建設(shè)置包,并添加到 iOS 應(yīng)用程序中。命名 Settings-Watch.bundle 包是為了與 iOS 應(yīng)用程序包進(jìn)行區(qū)分。
WatchKit 設(shè)置包的初始內(nèi)容與 iOS 應(yīng)用程序設(shè)置包相同,詳見清單 12-1。清單 12-1 WatchKit 設(shè)置包的內(nèi)容
Settings-Watch.bundle/
Root.plist
en.lproj/
Root.strings
關(guān)于如何配置設(shè)置包內(nèi)容,請查看 Implementing an iOS Settings Bundle。有關(guān)設(shè)置包的詳細(xì)信息,請查看?Settings Application Schema Reference。
WatchKit 設(shè)置必須存儲在共享組容器中,iOS 應(yīng)用程序和 WatchKit 擴(kuò)展均可對其進(jìn)行訪問。因?yàn)?WatchKit 設(shè)置包位于 iOS 應(yīng)用程序,系統(tǒng)會默認(rèn)把參數(shù)值寫入iOS應(yīng)用程序容器。如果想訪問 WatchKit 擴(kuò)展,您必須對項(xiàng)目執(zhí)行以下配置:
Root.plist 文件添加 ApplicationGroupContainerIdentifier 鍵?!?當(dāng)配置 App Group 功能時,把此鍵所對應(yīng)索引設(shè)置為相同的標(biāo)示符。要想訪問存儲于一組容器中的參數(shù),請使用 initWithSuiteName: 方法來創(chuàng)建 NSUserDefaults 對象。調(diào)用此方法時,請指定組容器標(biāo)示符所用的字符串。然后使用用戶默認(rèn)對象來訪問參數(shù)值。下面提供了訪問自定義組的示例:
清單 12-2 訪問一個共享組容器的參數(shù)
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.example.MyWatchKitApp"];
BOOL enabled = [defaults boolForKey:@"enabled_preference"];
如何訪問參數(shù)的值,更多信息請參考 NSUserDefaults Class Reference。