App and Extension - Use Core data == error : sharedApplication()' is unavailable

后端 未结 3 822
Happy的楠姐
Happy的楠姐 2020-12-20 06:16

I\'m trying to read/write data in extra class file which is public. (StoreData.swift)

My function :

  func FetchName (NameforDate: String) -> NSSt         


        
相关标签:
3条回答
  • 2020-12-20 06:47

    Your issue:

    StoreData.swift:115:49: 'sharedApplication()' is unavailable: Use view controller based solutions where appropriate instead.

    Is because -[UIApplication sharedApplication] is not available to extensions. Your extension does not run as part of your application, so there is no application context for an extension to message.

    This is clearly explained in the App Extension Programming Guide section on Understanding How an App Extension Works:

    Because of its focused role in the system, an app extension is ineligible to participate in certain activities. An app extension cannot:

    • Access a sharedApplication object, and so cannot use any of the methods on that object

    0 讨论(0)
  • 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];
    

    It works exactly like [NSUserDefaults standardUserDefaults] so you can store a minimal part of your data but it's all you can do.

    EDIT:

    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:

    EDIT 2:

    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/

    0 讨论(0)
  • 2020-12-20 07:09

    If you need a managed object context you can create your own within your extension.Your AppDelegate will not be available to you. I would suggest moving out that from your app delegate to a class you can share between both. You will still be able to listen for core data updates so they don't need to share contexts/persistent store coordinates.

    EDIT:

    I'd like to point out that extensions are essentially a different sandbox. Therefore if you create a shared class the instances will not be the same shared between App and Extension. Therefore making the persistent store coordinator and contexts different.

    0 讨论(0)
提交回复
热议问题