Preloading data into core data in iOS 8 app - ios

I am making a swift app, where I need to preload core data. For this, I created another sample iOS app which uses exactly same datamodel as main app. This sample creates sqlite file with data in it. I copied the sqlite files (.sqlite, and 2 .sqlite-*) created by sample app with data to the resource bundle of main app and my code in "persistentStoreCoordinator" is as shown below.
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: NSURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("myAssistant.sqlite")
//----------------------------------------------------------------------------
// Add the below code
// Check if a data store already exists in the documents directory.
var checker: Bool = NSFileManager.defaultManager().fileExistsAtPath(url.path!)
if (!checker){
// If there’s no Data Store present (which is the case when the app first launches), identify the sqlite file we added in the Bundle Resources, copy it into the Documents directory, and make it the Data Store.
var sqlitePath: NSString = NSBundle.mainBundle().pathForResource("myAssistant", ofType: "sqlite")!
NSFileManager.defaultManager().copyItemAtPath(sqlitePath, toPath: url.path!, error: nil)
}
//----------------------------------------------------------------------------/
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(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 \(error), \(error!.userInfo)")
abort()
}
However, main app crashes with below error.
2015-02-19 18:23:37.235 myAssistant[10477:488435] CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/NishiJain/Library/Developer/CoreSimulator/Devices/428084BE-0E2B-4F58-A274-AED2C76845DF/data/Containers/Data/Application/7F478A95-CD1E-4C99-BF62-60DAA39C6C11/Documents/myAssistant.sqlite options:(null) ... returned error Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x7f9c11e4e760 {metadata={
NSPersistenceFrameworkVersion = 519;
NSStoreModelVersionHashes = {
Category = <be1d87d2 e4c72a88 a830fb54 b9aea852 7887b5a6 bf2f85bb 22e878d0 c6916d06>;
ListDetails = <2cc64684 6520b473 d4bc4ae5 39f66fa0 0437788e ef1a0d91 1bdd7b52 86c0fbf2>;
Lists = <c2491da1 58622f56 64112d31 ba3e294a 1167e3f1 5427cd3a a56c1613 e2c0ee8a>;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "F84E0B5C-F83B-48ED-9043-5F9B6752FCA4";
"_NSAutoVacuumLevel" = 2;
}, reason=The model used to open the store is incompatible with the one used to create the store} with userInfo dictionary {
metadata = {
NSPersistenceFrameworkVersion = 519;
NSStoreModelVersionHashes = {
Category = <be1d87d2 e4c72a88 a830fb54 b9aea852 7887b5a6 bf2f85bb 22e878d0 c6916d06>;
ListDetails = <2cc64684 6520b473 d4bc4ae5 39f66fa0 0437788e ef1a0d91 1bdd7b52 86c0fbf2>;
Lists = <c2491da1 58622f56 64112d31 ba3e294a 1167e3f1 5427cd3a a56c1613 e2c0ee8a>;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "F84E0B5C-F83B-48ED-9043-5F9B6752FCA4";
"_NSAutoVacuumLevel" = 2;
};
reason = "The model used to open the store is incompatible with the one used to create the store";
}
2015-02-19 18:23:37.243 myAssistant[10477:488435] Unresolved error Optional(Error Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed to initialize the application's saved data" UserInfo=0x7f9c11f27600 {NSLocalizedFailureReason=There was an error creating or loading the application's saved data., NSLocalizedDescription=Failed to initialize the application's saved data, NSUnderlyingError=0x7f9c11e4e7a0 "The operation couldn’t be completed. (Cocoa error 134100.)"}), Optional([NSLocalizedFailureReason: There was an error creating or loading the application's saved data., NSLocalizedDescription: Failed to initialize the application's saved data, NSUnderlyingError: Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x7f9c11e4e760 {metadata={
NSPersistenceFrameworkVersion = 519;
NSStoreModelVersionHashes = {
Category = <be1d87d2 e4c72a88 a830fb54 b9aea852 7887b5a6 bf2f85bb 22e878d0 c6916d06>;
ListDetails = <2cc64684 6520b473 d4bc4ae5 39f66fa0 0437788e ef1a0d91 1bdd7b52 86c0fbf2>;
Lists = <c2491da1 58622f56 64112d31 ba3e294a 1167e3f1 5427cd3a a56c1613 e2c0ee8a>;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "F84E0B5C-F83B-48ED-9043-5F9B6752FCA4";
"_NSAutoVacuumLevel" = 2;
}, reason=The model used to open the store is incompatible with the one used to create the store}])
I tried solutions posted on this site (like deleting app from simulator, clean & build, Reset "Contents & Setting" in simulator) but none is working in my case.
Thanks in advance

In iOS programming, each program is installed in a sand box meaning that they are independent. An app cannot access data from another app, unless the other app allows such action.
In your case, there is an easier way to preload data. You can store your data in user defaults. On start of your app, you check if the data in user default is nil. If so, load data in user default (preload). Then in future, since there is data in user default, do not load again.

Related

Is there any other way than `UserDefaults` to share data between `Today Widget Extension` and the main `Container Application` in iOS

I mean I want to know that is it possible to use CoreData which shares a common resource?
You have the options of sharing the SQLite and user default between your main app and the widgets.
If you want the SQLite to be shared between the Main App and the widget, please follow the steps.
create an app group. Click on the main project -> Capabilities -> App Group -> create a group.. example: group.com.appname.appgroup
While creating the persistent coordinator, create an SQLite file in the app group and provide the path.
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
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let directory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.appname.appgroup")!
let url = directory.appendingPathComponent("somename.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: [NSMigratePersistentStoresAutomaticallyOption:true,NSInferMappingModelAutomaticallyOption:true])
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason 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}()
You can access the core data in widgets like the way you use in main app.
If you want to use the user defaults, then follow the below steps.
create a user deafult object.
var userDefaults =
UserDefaults(suiteName:"group.com.appname.appgroup")!
use this object for setting and retrieving the values.
You can share data between extensions and the host app via Keychain Sharing and App Groups (needs to be configured in the capabilities of your target).
Example for Keychain Sharing with KeychainAccess:
import KeychainAccess
let sharedKeychain = Keychain(service: "com.company.App.shared" , accessGroup: "TeamId.App")
sharedKeychain?["username"] = "Test"
Example for User Defaults:
var userDefaults = UserDefaults(suiteName: "group.com.company.App")!
Example for data in App Group:
let fileUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.company.App")!
To share data via CoreData just put the database file into the App Group storage.
Example with CoreStore:
import CoreStore
let dataStack: DataStack = {
let dataStack = DataStack(xcodeModelName: "App")
let storagePathUrl = fileUrl.appendingPathComponent("App.sqlite")
do {
try dataStack.addStorageAndWait(SQLiteStore(fileURL: storagePathUrl, configuration: "Default", localStorageOptions: .
recreateStoreOnModelMismatch))
} catch let error {
print("Cannot set up database storage: \(error)")
}
return dataStack
}()

Using CoreData to save and retrieve data from TextFields

Program Info
Hi! First question i've posted on Stackoverflow, so here it goes:
I am currently writing a program for used part inspection and need to be able to save the customer info using Core Data (or something else, if it is recommended). I just need to save it and then retrieve it to make a PDF.
Issues
-I am getting an error upon hitting the save button that says :
-I have no clue how to retrieve the data and convert it to PDF ( but thats a separate issue entirely)
Error
*2016-06-17 11:15:54.336 NewParts[6803:2846480] CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///var/mobile/Containers/Data/Application/1AAF2587-19C6-424F-BA3A-F37BBEE4AC71/Documents/SingleViewCoreData.sqlite options:(null) ... returned error Error Domain=NSCocoaErrorDomain Code=134100 "The managed object model version used to open the persistent store is incompatible with the one that was used to create the persistent store." UserInfo={metadata={
NSPersistenceFrameworkVersion = 641;
NSStoreModelVersionHashes = {
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "F4F8EB7F-B2EB-4D7F-A2A3-45FA91F8582E";
"_NSAutoVacuumLevel" = 2;
},*
Save Button Action
#IBAction func saveButton(sender: AnyObject)
{
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext
var entity1 = NSEntityDescription.insertNewObjectForEntityForName("UsedInfo", inManagedObjectContext:context) as NSManagedObject
entity1.setValue("Test", forKey: "product")
do {
try context.save()
}
catch {
print("error")
}
}
Error that you've post actually have an explanation
Code=134100 The managed object model version used to open the
persistent store is incompatible with the one that was used to create
the persistent store
If your app is not published on the AppStore, you can simply remove app from the device (or simulator), Clean project and do Build&Run.
Whenever you make changes to Core Data definition you should delete the app and rebuild.
If your app is on AppStore, you should perform Core Data migration, you can find a lot of information on the Internet.
Apple Core Data Model Versioning and Data Migration, explains how to perform Automatic Lightweight Migration :
You request automatic lightweight migration using the options
dictionary you pass in
addPersistentStoreWithType:configuration:URL:options:error:, by
setting values corresponding to both the
NSMigratePersistentStoresAutomaticallyOption and the
NSInferMappingModelAutomaticallyOption keys to YES:
Which means that you can pass following options to your persistent coordinator :
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
coordinator.addPersistentStoreWithType(NSSQLiteStoreType,configuration: nil,URL : storeURL, options as! [NSObject : AnyObject])

"Can't add the same store twice" on migration of Core Data versions

I am trying to perform a migration between two versions of CoreData that differ fundamentally to the fact that the new version has two configurations so I can save entities in two different sqlite file (one read-only in Main Bundle and one, the old sqlite, used now only for user data). I also added a model mapping to map the differences, especially to reset relationships between the entities that are lost due to multiple configurations.
The app works properly without crash if installed from scratch and new records are inserted in user data sqlite in application documents directory as expected.
The problem is when I try a migration from previous Core Data version: the app start without crash but on first executeFetchRequest it crash at coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: "Userdata", URL: urlUser, options: optionsUser, error: &errorUser) (viewed with debug) and console return this log:
2015-02-23 18:48:24.052 MedAbility[21480:585606] CoreData: error:
-addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Volumes/Documenti/Users/andrea/Library/Developer/CoreSimulator/Devices/301801BE-4B6A-4371-BE66-3E71557B0897/data/Containers/Data/Application/FBEC0124-1D74-4F94-99F2-6F492281AA8E/Documents/MedAbility.sqlite
options:{
NSInferMappingModelAutomaticallyOption = 1;
NSMigratePersistentStoresAutomaticallyOption = 1; } ... returned error Error Domain=NSCocoaErrorDomain Code=134080 "The operation
couldn’t be completed. (Cocoa error 134080.)" UserInfo=0x7fb50ae481d0
{NSUnderlyingException=Can't add the same store twice} with userInfo
dictionary {
NSUnderlyingException = "Can't add the same store twice"; } 2015-02-23 18:48:24.061 MedAbility[21480:585606] CoreData: error:
-addPersistentStoreWithType:SQLite configuration:Userdata URL:file:///Volumes/Documenti/Users/andrea/Library/Developer/CoreSimulator/Devices/301801BE-4B6A-4371-BE66-3E71557B0897/data/Containers/Data/Application/FBEC0124-1D74-4F94-99F2-6F492281AA8E/Documents/MedAbility.sqlite
options:{
NSInferMappingModelAutomaticallyOption = 1;
NSMigratePersistentStoresAutomaticallyOption = 1; } ... returned error Error Domain=NSCocoaErrorDomain Code=134080 "The operation
couldn’t be completed. (Cocoa error 134080.)" UserInfo=0x7fb50ae481d0
{NSUnderlyingException=Can't add the same store twice} with userInfo
dictionary {
NSUnderlyingException = "Can't add the same store twice"; }
This is my code:
Old version PersistentStoreCoordinator:
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MedAbility.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
// Set options for migrations
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options, 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(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSLog("Unresolved error \(error), \(error!.userInfo)")
}
// Exclude db from backup
Util.addSkipBackupAttributeToItemAtURL(url)
return coordinator
}()
New version PersistentStoreCoordinator:
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 = NSBundle.mainBundle().URLForResource("MedAbilityDomande", withExtension: "sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
// Set questions sqlite as read-only
let options = [NSReadOnlyPersistentStoreOption: true]
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: "Domande", URL: url, options: options, 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(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSLog("Unresolved error \(error), \(error!.userInfo)")
}
let urlUser = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MedAbility.sqlite")
var errorUser: NSError? = nil
var failureReasonUser = "There was an error creating or loading the application's saved data."
// Set migration options
let optionsUser = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: "Userdata", URL: urlUser, options: optionsUser, error: &errorUser) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReasonUser
dict[NSUnderlyingErrorKey] = errorUser
errorUser = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
NSLog("Unresolved error \(errorUser), \(errorUser!.userInfo)")
}
return coordinator
}()
Someone know how can I resolve this issue?
Thanks for the help!
EDIT
I did some test and I found that commenting coordinator!.addPersistentStoreWithType (NSSQLiteStoreType, configuration: "Questions", URL: url, options: options, error: & error) for the first database, the application starts without issues, obviously without the content of the database not added. If I reverse the addition of the two database the app crashes with same log except for "URL: file:[...]" that it's called on the ex-first now-second database ("MedAbilityDomande.sqlite"); in practice it's the addition of the second database the problem and not a specific database. It seems that migrating the old database to the new one used for user data actually doesn't migrate configurations, so remains the old configuration that goes to overlap the entities with the new read-only database inserted into the mainBundle. As I have previously said if the app start from scratch (without migration) works perfectly.
Do you have any idea?
Thank you so much again!
I finally found the solution! I created the database MedAbilityDomande.sqlite based on the database that after I wanted to migrate to use for user data. This brought to have two databases with same UUID generating the error "Can't add the same store twice". It was enough to change the UUID of the database in the application bundle (MedAbilityDomande.sqlite) and everything worked great.
Until next time!

swift: unable to add core data to existing project - tried everything

I have tried all suggestions and solutions given in questions similar to mine, but i am still not able to add new core data to the existing project. Things i tried:
Added new core data file to a simple application project
Copied the core data file from older project that works
Created a blank new project with Core Data selected and then added all my files.
Modified/Updated/Cross checked AppDelegate several times.
But theres is one thing i have noted:
When i copy the core data file from older project to the current, it gives error as fatal error: unexpectedly found nil while unwrapping an Optional value
whereas, when i make a new core data file, then there is a biggg error as shown below
CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/raunekk/Library/Developer/CoreSimulator/Devices/9CDAADD4-E413-4955-AF1B-9FBBB2B8E691/data/Containers/Data/Application/4FF507C8-9F5B-4982-B3B7-AAAF1F377FC0/Documents/MarineInsight.sqlite options:(null) ... returned error Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x7fc90b63eaf0 {metadata={
NSPersistenceFrameworkVersion = 519;
NSStoreModelVersionHashes = {
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "C8B3DC24-E463-4328-8459-56124E1E5B4D";
"_NSAutoVacuumLevel" = 2;
}, reason=The model used to open the store is incompatible with
the one used to create the store} with userInfo dictionary {
metadata = {
NSPersistenceFrameworkVersion = 519;
NSStoreModelVersionHashes = {
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "C8B3DC24-E463-4328-8459-56124E1E5B4D";
"_NSAutoVacuumLevel" = 2;
};
reason = "The model used to open the store is incompatible with
the one used to create the store";
}
2015-01-28 18:50:32.951 MarineInsight[8820:2204891] Unresolved
error Optional(Error Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed
to initialize the application's saved data" UserInfo=0x7fc90b420cd0 {NSLocalizedFailureReason=There was an error creating or loading the application's saved data., NSLocalizedDescription=Failed to initialize the application's saved data, NSUnderlyingError=0x7fc90b63f510 "The operation couldn’t be completed. (Cocoa error 134100.)"}), Optional([NSLocalizedFailureReason: There was an error creating or loading the application's saved data., NSLocalizedDescription: Failed to initialize the application's saved data, NSUnderlyingError: Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x7fc90b63eaf0 {metadata={
NSPersistenceFrameworkVersion = 519;
NSStoreModelVersionHashes = {
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "C8B3DC24-E463-4328-8459-56124E1E5B4D";
"_NSAutoVacuumLevel" = 2;
}, reason=The model used to open the store is incompatible with
the one used to create the store}])
I am getting the Optional Value Error in AppDelegate in this function at line let modelURL
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("Blog", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)
}()
I am at my wits end..plsssss plsss help me

Importing pre-existing sqlite file and core data models with .xcdatamodel into newly created Swift application

Currently i am importing pre-existing sqlite file and core data models with .xcdatamodel into newly created Swift Application. It has two tables say A & B. Whenever i try to access A table rows. Its giving me the following error.
"The model used to open the store is incompatible with the one used to create the store"
When i searched for this error i found some solutions which i applied but did not work. Solutions already applied are :
Delete the application & install again.
Reset the entire simulator and run again.
I even restarted Xcode which to me is stupid. But still did not work.
Here is my code :
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url : NSURL! = NSBundle.mainBundle().URLForResource("db", withExtension: "sqlite")
println("Url :: \(url)")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
var options = NSMutableDictionary()
options[NSReadOnlyPersistentStoreOption] = true
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options, 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()
}
Can somebody help me out in this. Thanks.

Resources