Implement CoreData into an existing project using Swift - ios

I am currently using Xcode 6 beta 7 and decided I needed CoreData after already creating my project. I have looked at some of the questions already asking this for objective C along with watching videos on the subject but I seem to be getting the same error. As for my usage of the CoreData framework itself, I am pretty sure it is correct as I created another empty project (with the CoreData box checked) and followed the same implementation and it worked like a charm but there may be something wrong I'm doing there too. So here are the steps I followed to implement CoreData in my project in Swift.
Step 1: I added the CoreData framework through "Link Binary with Libraries" tab under "Build Phases"
Step 2: I then went to any of my .swift files which would need to implement CoreData (appDelegate.swift and one other file as of now) and added the line:
import CoreData
to the top.
Step 3: I created a data list with an entity called "cData", then made a class for it called "data.swift". Here is data.swift:
import UIKit
import CoreData
#objc( data )
class data: NSManagedObject {
#NSManaged var something : String
}
Step 4: I wrote the code to actually save the data in another file:
#IBAction func useCoreData(sender: AnyObject)
{
let AD : AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let ct : NSManagedObjectContext = AD.managedObjectContext!
let ent = NSEntityDescription.entityForName( "CData", inManagedObjectContext: ct )
var dat = data( entity: ent!, insertIntoManagedObjectContext: ct )
dat.something = someTextField.text
ct.save( nil )
println(dat)
}
Step 5: Here is where I believe I messed up, though I could be wrong. I created a new project on a separate Mac (so I could name it the same thing) and checked the CoreData box. I then copied the entire appDelegate.swift from this project to my current one. Here is my appDelegate.swift:
import UIKit
import CoreData
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "y.Simple_Grade" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// 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 = NSBundle.mainBundle().URLForResource("my_app", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("my_app.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError.errorWithDomain("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 \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
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
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation 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 \(error), \(error!.userInfo)")
abort()
}
}
}
}
Once the IBAction method "useCoreData" is called, I get a crash and the exception states "fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)" and states the offending line is in appDelegate.swift:
let modelURL = NSBundle.mainBundle().URLForResource("my_app", withExtension: "momd")!
Again, when I try this same CoreData implementation in another project that had the CoreData box checked from the get-go, it works like a charm. I saw a similar question like this (the user was getting the same error), but it doesn't seem like his problem was solved either.

You're getting an nil value there because the file it's looking for doesn't exist in your main bundle.
You need to copy your data model file from the other project you created to your main project. The file would be called something like My_App.xcdatamodeld and should be located in the same folder that your Xcode project file is in.
Note: The URLForResource line is looking for My_App.momd; that file is created by Xcode from My_App.xcdatamodeld when it compiles your project.

Related

How to fix ZONE_NOT_FOUND error in CloudKit Dashboard?

In my app I use CloudKit to sync Core Data data ("Use Core Data" and "Use CloudKit" checkboxes were checked when creating a project).
In AppDelegate.swift I did not change code below Core Data stack mark. In code I don't specified zone anywhere.
During development I tested app on my devices using same iCloud account. Sync worked well. After testing I deployed my Development schema to Production schema. Later, I published an app on App Store.
Now in CloudKit Dashboard, in Production > Telemetry module I see ZONE_NOT_FOUND errors with a count that equals to approximately number of my users.
I tested my app (now downloaded directly from App Store) on my friend devices — sync working, but one note: her devices were used during development, too (I connected them to my Mac and build and install app from Xcode a number of times).
Another note: when I go to Data module in Production section in CloudKit Dashboard, in Zone menu I see 2 options:
com.apple.coredata.cloudkit.zone
_defaultZone
And when I press "Query Records", I see my data rows only when com.apple.coredata.cloudkit.zone selected.
AppDelegate.swift:
import UIKit
import CoreData
import StoreKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Register for Remote Notifications
application.registerForRemoteNotifications()
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentCloudKitContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentCloudKitContainer(name: "AppTitle")
guard let description = container.persistentStoreDescriptions.first else {
fatalError("No Descriptions found")
}
description.setOption(true as NSObject, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
NotificationCenter.default.addObserver(self, selector: #selector(self.processUpdate), name: .NSPersistentStoreRemoteChange, object: nil)
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
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)")
}
}
}
#objc
func processUpdate(notification: NSNotification) {
operationQueue.addOperation {
// process notification
let context = self.persistentContainer.newBackgroundContext()
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
lazy var operationQueue: OperationQueue = {
var queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
return queue
}()
}
This error worries me, what can I do when app already in production to fix it, make it go away?
Given the facts:
CoreData+CloudKit sync is working
The ZONE_NOT_FOUND error occurs exactly once per user
And the assumption:
That you yourself are not querying for the zone directly.
I would not be too concerned about this error.
My thoughts:
Most likely, upon first usage after install, the CoreData+CloudKit integration is checking the existence of the conventional zone com.apple.coredata.cloudkit.zone used for syncing by querying it. When the integration hits the ZONE_NOT_FOUND error, it will create it.
Apple could be more graceful by querying all zones and checking the result. However, if you had plenty zones already configured, the trial-and-error methodology has a performance advantage.
That is, I strongly believe that you cannot do much about it.
I would still keep an eye on it if the error per user ratio increases.
However, a slight increase can still be explained if a user signs out of of iCloud and/or deletes their private database.
Best of luck!

unable to create a context in swift file

I need to fetch some data from CoreData and need to do it frequently and hence trying to create utility class for it.
When I try to create context for it, it gives me error and below is the code.
I added a new .swift file and pasted below code
import Foundation
import UIKit
import CoreData
class armyDataSource{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
}
really not sure what wrong I'm doing it here.
if you want to create a wrappper class for core data manager you can write class like given below code in a swift file with your implementation.
import UIKit
import CoreData
class CoreDataManager {
static let sharedManager = CoreDataManager()
private init() {} // Prevent clients from creating another instance.
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "StackOF")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
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)")
}
}
}
}
You cannot initialize these properties like that in a class. You need to do this initialization in a method, best in the init call.
Cannot use instance member 'appDelegate' within property initializer; property initializers run before 'self' is available
So this means that you cannot use a property to initialize another property because this is all done before the init is called and self is fully available.
Try this instead:
class armyDataSource {
let appDelegate: UIApplicationDelegate
let context: NSManagedObjectContext
init() {
appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
}
}

Swift compiler error while adding Core Data to existing project

I'm trying to add Core Data to my existing project. I've created a Core Data model and I've added some codes to the AppDelegate but I'm getting this error.
"lazy' may not be used on an already-lazy glob"
I copied this from a empty project and then I try to fix this error it says on my project
Value of type 'AppDelegate' has no member 'persistentContainer'
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "IOS_Swift_CoreData")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
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)")
}
}
}
The code you are using should be like this. i.e. inside AppDelegate curly braces.
You need to import CoreData as well.
import UIKit
import Coredata
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// Your AppDelegate code here...
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CoreDataTest")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
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)")
}
}
}
}

Swift Core Data codegen: no valid NSEntityDescription for my NSManagedObject

Update 1: I have changed some of the code in line with what is presented in the next of the Stanford lectures. I also removed the code I added to AppDelegate because I saw there was a name clash there. The error message remains the same.
I am developing an iOS app of my own while following the Stanford Developing iOS 10 Apps with Swift course. I am struggling with getting my database set up however. I have created a minimal example of the issue I am running into. I am trying to create an Extension for an Entity in my database. I am trying my best to follow the example code in the slides from Lecture 10 of the course, because I just specifically need to get this simple app finished. However there are certain obstacles I ran into that led me to make changes:
1) Although I am directed to set the Module to Current Product Module this does not work (xcode cannot find the files that way) so I am setting it to Global Namespace instead
2) The professor creates Tweet entities in his example using:
if let tweet = Tweet(context: context) {
tweet.text = “some string”
// more code
}
However this does not work, xcode complains that Tweet is not an optional (“initializer for conditional binding must have optional type”).
Those aside, in my example I am trying to do something very simple. I am just trying to set up a CoreData database and add an entry to it. The error message I get when I do so is:
“An NSManagedObject of class 'database_test.Subject' must have a valid NSEntityDescription.”
Here is the step-by-step of the code I generated to test this issue:
1) created a new Swift project using CoreData
2) Here is my AppDelegate.swift
//
// AppDelegate.swift
// database_test
//
import UIKit
import CoreData
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "database_test")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
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)")
}
}
}
}
3) Created Subject entity with one attribute (uniqueID). This is in the Global namespace (see linked). I do the Codegen for a Category/Extension. I then create Subject.swift and fix it to import CoreData and add some code for adding unique subjects:
//
// Subject.swift
// database_test
//
import UIKit
import CoreData
class Subject: NSManagedObject {
class func addSubject(adding newSubject: String, in context: NSManagedObjectContext) throws {
let request: NSFetchRequest<Subject> = Subject.fetchRequest()
request.predicate = NSPredicate(format: "uniqueID = %#", newSubject)
do {
let matches = try context.fetch(request)
if matches.count > 0 {
assert(matches.count==1, "Subject.addSubject - matches.count > 1")
}
} catch {
throw(error)
}
let subject = Subject(context: context)
subject.uniqueID = newSubject
}
}
4) Here are the codegen files from DerivedData:
// Subject+CoreDataProperties.swift
//
// This file was automatically generated and should not be edited.
//
import Foundation
import CoreData
extension Subject {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Subject> {
return NSFetchRequest<Subject>(entityName: "Subject");
}
#NSManaged public var uniqueID: String?
}
// database_test+CoreDataModel.swift
//
// This file was automatically generated and should not be edited.
//
import Foundation
import CoreData
5) I then test adding something to the database
//
// ViewController.swift
// database_test
//
// Created by Alex B on 2017-07-10.
// Copyright © 2017 Alex B. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
//let context = AppDelegate.viewContext
var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
testAdding(subjectID: "John")
}
func testAdding(subjectID: String) {
container?.performBackgroundTask { context in
try?Subject.addSubject(adding: subjectID, in: context)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Running this in the simulator I get terminating with uncaught exception of type NSException which traces back to Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'database_test.Subject' must have a valid NSEntityDescription.'

Call master app's function with NC widget?

how can I have my notification center today widget be able to call a function within my master app? I am trying to make an application that tracks when the device has activity by calling a function within the master app that logs an activity time in the core data.
code for logging the time and date
func insertNewObject(sender: AnyObject) {
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as! NSManagedObject
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(NSDate(), forKey: "timeStamp")
// Save the context.
var error: NSError? = nil
if !context.save(&error) {
// Replace this implementation 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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
I'm willing to put any code in the NC widget for this to work
EDIT- Actually I figured out that all I need to do is share a xcdataobject between the two.
If you want to be able to share code between your NC widget and master application, you need to put that code in a framework. The framework will then need to be added to both the master application and the NC widget.

Resources