Search code examples
iosobjective-ccore-datamagicalrecord

iOS - Core Data - Saving an object that contains an array of Objects


I'm just getting started with Core data, (and I'm also trying to use Magical Record). I'm creating a pretty simple Payment tracking app.

I would like to save a Payment object that has an array of Debtors. This is what my Payment object looks like

@class Debtor;

@interface Payment : NSObject
@property (strong, nonatomic) NSString *paymentAmountString;
@property (strong, nonatomic) NSString *titleString;
@property (strong, nonatomic) NSArray *debtorsArray;
@property (strong, nonatomic) NSDate *dueDate;
@property (strong, nonatomic) NSString *notesString;
@end

And the debtorsArray is an array of Debtor objects

@interface Debtor : NSObject
@property (strong, nonatomic) NSString *nameString;
@property (strong, nonatomic) NSString *amountOwedString;

How should I go about saving this object since it contains an array. Do I need to create two different Entities, with a relationship between Payment and Debtor? How exactly do I do this, and how would I ensure that they are fetched properly?


Solution

  • Create only one entity for Payment. You will have to use the 'Transformable' data type for your attribute debtorsArray within this entity.

    Then implement the following methods in your Debtor class:

    - (void)encodeWithCoder:(NSCoder *)aCoder{
        [aCoder encodeObject:self.nameString forKey:@"nameString"];
        [aCoder encodeObject:self.amountOwnedString forKey:@"amountOwnedString"];
    }
    
    -(id)initWithCoder:(NSCoder *)aDecoder{
        if(self = [super init]){
            self.nameString = [aDecoder decodeObjectForKey:@"nameString"];
            self.amountOwnedString = [aDecoder decodeObjectForKey:@"amountOwnedString"];
        }
        return self;
    }
    

    Entity should be fetched normally like any other fetch query.

    Hope this helps.