Nosrettap
Nosrettap

Reputation: 11320

How to add an object to a NSMutableArray that is stored in a CoreData iOS database?

I have an NSManagedObject subclass where absences is an NSMutableArray

@interface Record : NSManagedObject
@property (nonatomic, retain) id absences;
@end

I want to be able to add items to the absences array; however, if I do [myRecord.absences addObject:SomeObj the record does not save properly. It almost appears that the NSManagedObject does not know that I updated the absences array.

Nevertheless, if I add SomeObj to some localAray, then set myRecord.absences = localArray, the NSManagedObject saves correctly.

Can someone explain this behaviour and how I might avoid it...thanks

Upvotes: 0

Views: 383

Answers (1)

Dmitry Shevchenko
Dmitry Shevchenko

Reputation: 32394

You're exactly right, in the first case you're changing an object outside of NSManagedObject field of view. To solve this, Apple doc says the following

For mutable values, you should either transfer ownership of the value to Core Data, or implement custom accessor methods to always perform a copy.

So declaring your property with (copy) should suffice.

Upvotes: 1

Related Questions