应用和扩展 - 使用核心数据==错误:sharedApplication()'不可用 [英] App and Extension - Use Core data == error : sharedApplication()' is unavailable
问题描述
我正在尝试在公共的额外类文件中读/写数据。 (StoreData.swift)
I'm trying to read/write data in extra class file which is public. (StoreData.swift)
我的功能:
func FetchName (NameforDate: String) -> NSString
{
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
}
在哪里是(UIApplication.sharedApplication()。我得到了错误:
At line where is "(UIApplication.sharedApplication()." I get the error:
StoreData.swift:115:49:'sharedApplication()'不可用:使用view
基于控制器的解决方案相反。
StoreData.swift:115:49: 'sharedApplication()' is unavailable: Use view controller based solutions where appropriate instead.
我创建了App and Today Extension。
I created App and Today Extension.
推荐答案
要在App和Today Widget之间共享数据,遵循Apple指南,您必须在目标的功能选项卡下创建一个应用程序组,并将其链接到App和Widget。
To share data between App and Today Widget, following Apple guidelines, you have to create an App Group under target's capabilities tab and link it to both App and Widget.
要访问您的共享默认值:
To access your shared defaults:
NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:YOUR_APP_GROUP_ID];
它的工作方式与[NSUserDefaults完全相同standardUserDefaults]所以你可以存储你的数据的最小部分但是你可以做的就是。
It works exactly like [NSUserDefaults standardUserDefaults] so you can store a minimal part of your data but it's all you can do.
编辑:
在这里你可以找到套件默认值的Swift文档:
https://developer.apple.com/Library/mac/documentation/Cocoa/Reference/Foundation /Classes/NSUserDefaults_Class/index.html#//apple_ref/occ/instm/NSUserDefaults/initWithSuiteName :
Here you can find Swift doc for Suite Defaults: https://developer.apple.com/Library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html#//apple_ref/occ/instm/NSUserDefaults/initWithSuiteName:
编辑2:
使用Singleton代替访问您的Core数据,您可以在这里找到一个简单的教程:
http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/
Use a Singleton to access your Core Data instead, you can find an easy tutorial here: http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/
这篇关于应用和扩展 - 使用核心数据==错误:sharedApplication()'不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!