iOS 5 Core Data change

This will only be of interest to you in case you’re an iOS developer and you’re using Core Data. Anyone else – you can safely stop reading.

I’ve made the assumption in the past that NSManagedObjects persisted with Core Data return the same instances of their contained Mutable objects after the NSManagedObject has been deserialized and instanced. This seemed to be a valid (even if wrong) assumption under iOS 4, but is patently false under iOS 5. The NSManagedObject memory allocation scheme has apparently been changed in iOS 5 so that objects are stored in serialized form and deserialized on demand, so that you’ll now get a new autoreleased instance of each object on every accessor call. Hence you cannot ever check for pointer equality between copies of an object returned by Core Data on separate accessor calls – you’ll be getting a new instance on each call.

So, for example:

@interface DateHolder : NSManagedObject  {}
     @property (nonatomic, retain) NSDate *aDate;

@implementation DateHolder
     @dynamic aDate;

DateHolder* aHolder;
NSDate* aDateInstance = aHolder.aDate;
NSDate* aDateInstance2 = aHolder.aDate;

Under iOS 4, aDateInstance == aDateInstance2 (even if this is not apparently guaranteed), but under iOS 5 aDateInstance != aDateInstance2. The values are still obviously equal so ([aDateInstance isEqual:aDateInstance2] == TRUE).

Most apps and developers won’t notice, but there are instances where pointer comparison has been handy, but this is a total no-go route now. I suspect the change was motivated by the iDevice CPUs getting faster so the deserialization process for the devices is getting faster and faster while simultaneously the object graphs in apps is getting richer, and the change allows the device to hold more data in memory.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.