How to save the CGRect and color objects in CoreData iOS

Problem:

I want to save CGRect for some o my rectangle,Square and other objects.Also i want to save the color object in coreData.If i saved directly in coredata app crashes.



Solution:

In coredata you may not be able to save the drawing objects and color objects.So follow the steps to solve your problem.

1) Change the coredata attribute type to binary Data

2) Create an NSMutabledictionary.

3) Set integer and double values as NSNumber, Rect as NSValue and color as Data.



                    let dic = NSMutableDictionary.init()
                    dic.setValue(NSValue(cgRect: rect.Button.frame), forKey: "btnframe")
                    dic.setValue(NSNumber(integerLiteral:btn.tag), forKey: "tag")
                    dic.setValue(NSKeyedArchiver.archivedData(withRootObject: color), forKey: "color")


4) Add the dictionary to an array.

5) Then save array to the binarydata using nskeyarchiever like below


       coredata.value = NSKeyedArchiver.archivedData(withRootObject: array) as NSData


6)When retrieve the data from coredata unarchieve the data and get the dictionary values 


Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift