Wednesday, April 20, 2016

Adding an NSArray in Coredata

Just discovered how to add an NSArray property to Coredata.  I know I know, an NSSet is just fine and does everything you need, and you can convert it to NSArray if you need to.  But I just wanted to try this - I had a situation where I didnt need a whole new managed object class, I just wanted to store an array of NSNumbers.  Heres what you do :

First, add your property to the data model as usual, and make it a 'transformable' property (in my case the property is called actionRules) :

Then add the normal attribute to your coredata managed object header file (and here you can actually refer to it as an array)  :

And add the @dynamic to the main file :

Then some slightly more weird stuff.   You add an entirely separate @interface to the same header file, using the name of the new property, and setting it to NSValueTransformer (you literally put this after the @end of the normal interface) :


Finally, add this entirely new @implementation in the main file.  Before or after the other normal implementation is fine (obviously you need to change the 'ActionRules' for the name of your array) :

And thats it - you have an NSArray that you can use throughout your application as usual.  Obviously its not mutable, so to add properties, create a mutableCopy of it, change it as required, then set the property as this mutableArray.  Still, its quite handy I find, and theres the additional bonus of quickly organised indexing.





No comments:

Post a Comment

Social Network with Firebase 3 - Infinitely scrolling UITableView of Firebase Items

Ive already talked about the basics of a Firebase social network project , and adding posts in two other articles. Here I want to explain ...