[英]Share Core Data database between app and today extension in Swift
I have a database from which my widget has to read some data. 我有一个数据库,我的小部件必须从中读取一些数据。 I've set the membership targets to all the related files to both the app and the widget. 我已经将会员目标设置为应用程序和小部件的所有相关文件。 There is a problem though. 不过有一个问题。
I have a helper class in my main app that gets the AppDelegate context whenever i do some operations on the database. 我的主应用程序中有一个帮助程序类,每当我对数据库进行一些操作时,该类都会获取AppDelegate上下文。 The code looks as follows: 该代码如下所示:
class func getEntityAndContext(name:String) -> (entity:NSEntityDescription, context: NSManagedObjectContext){
var appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let entity:NSEntityDescription = NSEntityDescription.entityForName(name, inManagedObjectContext: context)!
return (entity, context)
}
This method helps me in cases like these: 这种方法在以下情况下对我有帮助:
class func getAll() -> Array<City>{
let (_, context) = NSManagedObjectWrapper.getEntityAndContext("City")
let req = NSFetchRequest(entityName: "City")
req.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true)]
let citiesList:Array<City> = context.executeFetchRequest(req, error: nil)! as Array<City>
return citiesList
}
After i added the target membership to the widget, i get this error: Use of undeclared type 'AppDelegate'
. 将目标成员资格添加到窗口小部件后,出现以下错误: Use of undeclared type 'AppDelegate'
。 It makes sense, but i have no idea how to fix it. 这是有道理的,但我不知道如何解决。 Can you please help me? 你能帮我么?
PS: I also noticed that i get this error too: Use of unresolved identifier 'NSFetchRequest'
. PS:我也注意到我也收到此错误: Use of unresolved identifier 'NSFetchRequest'
。 What am i doing wrong? 我究竟做错了什么? This surely can't be the way to do it... 这肯定不是做到这一点的方法...
I found an answer here: https://github.com/pjchavarria/Swift-Widget 我在这里找到了答案: https : //github.com/pjchavarria/Swift-Widget
This git project shows how to use core data in a widget. 这个git项目展示了如何在小部件中使用核心数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.