App 的核心是内容.那内容都有哪些方式存储呢?
我们知道在iOS中存储数据一般会用以下四种方式:
- NSKeyedArchiver:采用归档的形式来保存数据,一般NSString、NSDictionary、NSArray、NSData、NSNumber等类型,可以直接用NSKeyedArchiver进行归档和恢复.
- NSUserDefaults: 用来存储配置信息 特点是简单方便.通过[NSUserDefaults standardUserDefaults]获取实例来存储简单的数据。
- 数据库(Sqlite,Coredata)。存储大量的信息
- 文件存储:各种文件存储。通过沙盒来进行存储。
#####那Apple watch 端可以通过什么方式来存储呢?
- plist NSUserDefaults是快速共享信息的途径。它适合存储各种快速访问和计算的小型数据,比如用户名与档案信息。存储在Watch Extension中.
需要注意的是实现数据共享时候 你需要设定App Group来让设备通过共享容器来实现数据共享,确保手表扩展和ios target都已如此设置。基本上就是针对两个设备创建一个统一的App Group标识符,如下图所示:APP Groups 标识符为group.com.db.iwatch
let defaults=NSUserDefaults(suiteName: "group.com.db.iwatch")
watch extension端和 ios phone端就可以实现数据共享啦
- coredata watchos2 之后开始支持coredata啦。在watch 端怎么实现coredata 存储以及CRDU呢?
需要注意的是实现数据共享时候 APP Groups 标识符为group.com.db.iwatch
要了解coredata,就必须理解下面四个类所代表的意思,下面分别介绍:
- NSManagedObjectModel 代表了数据模型,也就是Xcode中创建的.xcdatamodel文件中所表诉的信息
- NSPersistentStore 是数据存放的地方,可以是SQLite、XML(仅OS X)、二进制文件、或仅内存中
- NSPersistentStoreCoordinator 是协调者,用来在NSManagedObjectContext和NSPersistentStore之间建立连接。
- NSManagedObjectContext 是应用程序唯一需要访问的类,其中提供了对数据操作的一系列接口。
- NSManagedObject 是具体某个Table 对应的实体对象
通过上面简单的描述来写下面Watch端关于 首先初始化新建一个WatchCoreDataProxy.swift文件,通过该类来操作数据库。
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对应的位置
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范问数据库的句柄
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
//保存数据库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数据库中添加Songs Table
然后通过Editor 按钮 Create NSManagerObject SubClass 产生如下类
extension Songs {
@nonobjc public class func fetchRequest() -> NSFetchRequest {
return NSFetchRequest(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?
}
复制代码
创建添加一条记录到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)")
//对数据进行存储.
DataBaseManager.saveManagedContext()
}
复制代码
查询所有歌曲如下图所示:
public func fetchAllSongs(sortKey:String = "createTime")->[Songs]{
let fetchRequest = NSFetchRequest(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
}
复制代码
###总结:
WatchOS可以通过coredata来存储复杂的数据,plist来存储较为简单的数据,要实现app与watch 共享数据需要注意添加APP Groups 标识符.