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?

Answers


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.


Need Your Help

Accessing a List object stored as a session variable in javascript

javascript asp.net json oop

I have a list of id's stored in my ASP.NET application's session. For contextual purposes:

CSS + jQuery toggle menu

javascript jquery html css menu

I am working on a menu using jQuery + CSS3.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.