App 的核心是內(nèi)容.那內(nèi)容都有哪些方式存儲呢?
我們知道在iOS中存儲數(shù)據(jù)一般會用以下四種方式:
- NSKeyedArchiver:采用歸檔的形式來保存數(shù)據(jù),一般NSString、NSDictionary、NSArray、NSData、NSNumber等類型,可以直接用NSKeyedArchiver進行歸檔和恢復(fù).
- NSUserDefaults: 用來存儲配置信息 特點是簡單方便.通過[NSUserDefaults standardUserDefaults]獲取實例來存儲簡單的數(shù)據(jù)。
- 數(shù)據(jù)庫(Sqlite,Coredata)。存儲大量的信息
- 文件存儲:各種文件存儲。通過沙盒來進行存儲。
那Apple watch 端可以通過什么方式來存儲呢?

- plist
NSUserDefaults是快速共享信息的途徑。它適合存儲各種快速訪問和計算的小型數(shù)據(jù),比如用戶名與檔案信息。存儲在Watch Extension中.
需要注意的是實現(xiàn)數(shù)據(jù)共享時候
你需要設(shè)定App Group來讓設(shè)備通過共享容器來實現(xiàn)數(shù)據(jù)共享,確保手表擴展和ios target都已如此設(shè)置?;旧暇褪轻槍蓚€設(shè)備創(chuàng)建一個統(tǒng)一的App Group標(biāo)識符,如下圖所示:APP Groups 標(biāo)識符為group.com.db.iwatch
let defaults=NSUserDefaults(suiteName:
"group.com.db.iwatch")
watch extension端和 ios phone端就可以實現(xiàn)數(shù)據(jù)共享啦
- coredata
watchos2 之后開始支持coredata啦。在watch 端怎么實現(xiàn)coredata 存儲以及CRDU呢?
需要注意的是實現(xiàn)數(shù)據(jù)共享時候
APP Groups 標(biāo)識符為group.com.db.iwatch
要了解coredata,就必須理解下面四個類所代表的意思,下面分別介紹:
- NSManagedObjectModel
代表了數(shù)據(jù)模型,也就是Xcode中創(chuàng)建的.xcdatamodel文件中所表訴的信息 - NSPersistentStore
是數(shù)據(jù)存放的地方,可以是SQLite、XML(僅OS X)、二進制文件、或僅內(nèi)存中 - NSPersistentStoreCoordinator
是協(xié)調(diào)者,用來在NSManagedObjectContext和NSPersistentStore之間建立連接。 - NSManagedObjectContext
是應(yīng)用程序唯一需要訪問的類,其中提供了對數(shù)據(jù)操作的一系列接口。 - NSManagedObject
是具體某個Table 對應(yīng)的實體對象
通過上面簡單的描述來寫下面Watch端關(guān)于
首先初始化新建一個WatchCoreDataProxy.swift文件,通過該類來操作數(shù)據(jù)庫。
public class WatchCoreDataProxy: NSObject {
let sharedAppGroup:String = "group.com.db.iwatch"
//初始化單例該類
public class var sharedInstance : WatchCoreDataProxy {
struct Static {
static let instance : WatchCoreDataProxy = WatchCoreDataProxy()
}
return Static.instance
}
// MARK: - Core Data stack
public lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.makeandbuild.ActivityBuilder" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in:.userDomainMask )
return urls[urls.count-1]
}()
//
public lazy var managedObjectModel: NSManagedObjectModel = {
// let proxyBundle = Bundle(identifier: "com.db.iwatch.WatchCoreDataProxy")
//注意此處是Model名稱,xcdatamodel對應(yīng)的位置
let modelURL = Bundle.main.url(forResource: "Model", withExtension: "momd")
//let proxyBundle = Bundle(identifier: "com.makeandbuild.WatchCoreDataProxy")
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
//let modelURL = proxyBundle?.url(forResource: "Model", withExtension: "momd")
return NSManagedObjectModel(contentsOf: modelURL!)!
}()
public lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
//注意這里的shareAppGroup
var sharedContainerURL: URL? = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: self.sharedAppGroup) as URL?
if let sharedContainerURL = sharedContainerURL {
let storeURL = sharedContainerURL.appendingPathComponent("Model.sqlite")
print("the database mode url is:\(storeURL)")
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data." as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}
return nil
}()
//mangedObjectContext范問數(shù)據(jù)庫的句柄
public lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
//保存數(shù)據(jù)庫Context
public func saveContext () {
let context = self.managedObjectContext!
if (context.hasChanges) {
do {
try
context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
下面在coredata數(shù)據(jù)庫中添加Songs Table

然后通過Editor 按鈕 Create NSManagerObject SubClass 產(chǎn)生如下類
extension Songs {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Songs> {
return NSFetchRequest<Songs>(entityName: "Songs");
}
@NSManaged public var albumId: String?
@NSManaged public var coverUrl: String?
@NSManaged public var createTime: String?
@NSManaged public var duration: String?
@NSManaged public var favorite: Int16
@NSManaged public var name: String?
@NSManaged public var songId: String?
@NSManaged public var sourceUrl: String?
@NSManaged public var artist: String?
}
創(chuàng)建添加一條記錄到Song字段中去
public func createSong(songTmp:SongsModel){
let song:Songs = NSEntityDescription.insertNewObject(forEntityName: SongManager.SONG_DATABASE, into: DataBaseManager.getContext()) as! Songs
print("will insert songMode :\(songTmp)")
song.albumId = songTmp.albumId
song.name=songTmp.songName
song.songId=songTmp.songId
song.duration=songTmp.duration
song.artist=songTmp.atrtisName
song.coverUrl=songTmp.coverUrl
song.favorite=Int16(songTmp.favorite!)!
song.sourceUrl=songTmp.sourceUrl
let time = Date().timeIntervalSince1970
song.createTime = String.init(format: "%lld", time)
print("the name is:\(song.name)")
//對數(shù)據(jù)進行存儲.
DataBaseManager.saveManagedContext()
}
查詢所有歌曲如下圖所示:
public func fetchAllSongs(sortKey:String = "createTime")->[Songs]{
let fetchRequest = NSFetchRequest<Songs>(entityName: SongManager.SONG_DATABASE)
let sortDescriptor = NSSortDescriptor(key: sortKey, ascending: true)
fetchRequest.sortDescriptors=[sortDescriptor]
var fetchedSongs:[Songs]=[]
do {
fetchedSongs = try DataBaseManager.getContext().fetch(fetchRequest)
} catch{
print("Failed to fetch employees: \(error)")
}
return fetchedSongs
}
總結(jié):
WatchOS可以通過coredata來存儲復(fù)雜的數(shù)據(jù),plist來存儲較為簡單的數(shù)據(jù),要實現(xiàn)app與watch 共享數(shù)據(jù)需要注意添加APP Groups 標(biāo)識符.