Using Transformable && Binary Data properties in Core Data:
As you know Core Data attributes can have properties like Undefined, Integer16, Integer32, Integer64, Float, Decimal, Date, Boolean, String, Double, Binary Data in Objective C has to offer. Out of all of these properties Binary Data is must to be considered.
With the support of all of these properties Swift language is also providing you Transformable property which is very Interestingly Important. Because of this property you can put any type of data into the Core Data without extra overhead. In this tutorial I am going to show you how to use both of these properties...(Binary Data && Transformable property).
1. As usual create a singleView template application && name it "ImportantDataTypeInCoreData" && choose language as swift Leaving Core Data checkbox Unchecked we will Insert our Core Data model later. as shown in Image below:
2. Add a song whose URL we will be storing into the "urlOfSong" attribute we will be creating in model shortly.
3. Now that we have a project to complete && we will be using Core Data properties so now create a Cocoa Touch class with name "Persistence" which is subclass of NSObject
&& then for including model click on the "ImportantDataTypeInCoreData" folder && click on New File -> Core Data (iOS field) ->Data Model && name it "properties" then continue until it will be created as shown in Image:
4. Now open the model you just created && add an entity named "UseOfDataTypes" with two attributes "urlOfSong" && "name" of type "Transformable" && "Binary Data" respectively, shown in the Image below:
5. Keep the entity "UseOfDataTypes" selected we are going to create a NSObject Class. Click on the editor && then click on the Create NSmanagedObject Subclass option && follow the instructions until the class with the same name as entity will be created.
NSObject subclass is created with the name same a entity "UseOfDataTypes" open it && you will see something like what shown in the below presented Image:
As shown in this Image "urlOfSong" attribute is of type "AnyObject" because it is of Transformable type && this has to be transformed in to what we need to store in Core Data && name is of type NSData because we set it to Binary Data in the model. Go ahead && transform your class into somewhat shown in the below Image:
"urlOfSong" attribute is of type NSURL now, since we want to store the url of string to Core Data Model.
6. Now add the following code to your Persistence.Swift file we created earlier.:
//returning the path of document directory of the application
class var applicationDocumentDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex - 1] as NSURL
}
func saveContext() { //saving the data into data store
if let moc = self.managedObjectContext {
var error : NSError? = nil
if moc.hasChanges && !moc.save(&error) {
abort()
}
}
}
//creating ManagedObjectContext && Coordinator && Model
var managedObjectContext : NSManagedObjectContext? = {
let modelURL = NSBundle.mainBundle().URLForResource("properties", withExtension: "momd")
let managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL!)
let storeURL = Persistence.applicationDocumentDirectory.URLByAppendingPathComponent("properties.sqlite")
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel!)
var error : NSError? = nil
if (persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType , configuration: nil, URL: storeURL, options: nil, error: &error) == nil) {
abort()
}
let managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
return managedObjectContext
}()
Here in the above displayed code all we are doing is just getting the Path where we store the model that we created named as "properties.xcdatamodeld" && then creating the persistence store coordinator && ManagedObjectModel && Context.
------>>>>>> Now we have everything setup add following code to Persistence.Swift File for storing objects to Core Data :
func createObjects() {
let anyObject = NSEntityDescription.insertNewObjectForEntityForName("UseOfDataTypes", inManagedObjectContext: managedObjectContext!) as? UseOfDataTypes
let path = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("pooja", ofType: "mp3")!)
anyObject?.urlOfSong = path! as NSURL
var archievedName = NSKeyedArchiver.archivedDataWithRootObject(Name)
//archiving the data to store in Core Data for Binary Data attribute
//archiving the data to store in Core Data for Binary Data attribute
anyObject?.name = archievedName
saveContext()
}
------->>>>>> Here is some code to Fetch Object From Core Data:
func fatchedTracks() -> [UseOfDataTypes] {
var error: NSError? = nil
let fetchRequest = NSFetchRequest(entityName: "UseOfDataTypes")
var returnedObject = self.managedObjectContext?.executeFetchRequest(fetchRequest, error: &error) as [UseOfDataTypes]
return returnedObject
}
------>>>>>> Here is function to delete objects if existing to store:
func deleteAllObjectsForEntityWithName(name: String) {
println("deleting all objects in entity \(name)")
var fetchRequest = NSFetchRequest(entityName: name)
if let ManagedObjectContext = self.managedObjectContext {
var error: NSError? = nil
let objectIDs = ManagedObjectContext.executeFetchRequest(fetchRequest, error: &error)
for objectID in objectIDs! {
ManagedObjectContext.deleteObject(objectID as NSManagedObject)
}
saveContext()
println("All objects in entity \(name) deleted")
}
}
--->>>>>>Add all these above declared functions to the Persistence.Swift Class.<<<<--------
7. Now open the ViewController.Swift File && add following bit of code to viewDidLoad() function...
override func viewDidLoad() {
super.viewDidLoad()
for var i = 0; i < returnedData.count; i++ {
let path = returnedData[i].valueForKey("urlOfSong") as NSUR
println()
println(path)
var unarchievedName = NSKeyedUnarchiver.unarchiveObjectWithData(returnedData[i].valueForKey("name") as NSData) as String
//unarchiving the archived data coming from Core Data
println()
println(unarchievedName)
}
}
Here all we are doing is just getting the data from persistence store && displaying it to the console. Remember we did't add any graphics in this project.
8. Now the final step is to open you AppDelegate.Swift file && add below written code to the "application: applicationDidFinishLaunchingWithOptions()" function
persistence = Persistence()
self.persistence?.deleteAllObjectsForEntityWithName("UseOfDataTypes")
self.persistence?.createObjects()
self.persistence?.saveContext()
if let persistence = persistence {
returnedData = persistence.fatchedTracks()
}
Your Appdelegate.Swift file should looks like:
9. Now well guys Build your application && when the white Screen on to the simulator shows then see the console of Xcode you will have output somewhat like this:
Well guys guess what this is all.....this app was a marathon but these are the properties that should be learnt && Once mastered you will be enjoying tackling problems of Core Data.....As Usual Go Ahead & Practice these properties...........
No comments:
Post a Comment