Proper use of awakeFromInitializer

51 views
Skip to first unread message

Brendan Duddridge

unread,
Jul 20, 2015, 11:52:32 PM7/20/15
to mobile-c...@googlegroups.com
Hi,

So in my awakeFromInitializer I am trying to setup some default values for my model objects. The problem I'm finding is that when I load my models from the database, awakeFromInitializer is being called and overwriting the properties on my model that were read from the database.

So I thought I would add a check to make sure the model object is new before I set my properties:

- (void)awakeFromInitializer {

       [super awakeFromInitializer];

       if (self.isNew) {

               self.name = NSLocalizedString(@"New Field", @"");

               self.fieldType = kFieldTypeText;

       }
}

But that didn't work either because my code inside if statement never gets called after I create my model object. I would think that isNew would be true, but it appears to be false when newly created.

This is how I'm creating my model objects, so maybe this is the problem:

CBLDocument *fieldDoc = [database documentWithID:[@"fld-" stringByAppendingString:[Utilities compactUniqueString]]];

TFField *newField = [TFField modelForDocument:fieldDoc];

newField.type = NSStringFromClass([TFField class]);


Am I doing anything wrong here?

Thanks,

Brendan

Jens Alfke

unread,
Jul 21, 2015, 1:16:22 PM7/21/15
to mobile-c...@googlegroups.com

On Jul 20, 2015, at 8:52 PM, Brendan Duddridge <bren...@gmail.com> wrote:

But that didn't work either because my code inside if statement never gets called after I create my model object. I would think that isNew would be true, but it appears to be false when newly created.

That surprised me so I went and looked at the code. isNew is set when the model is created by +modelForNewDocumentInDatabase:, but not by +modelForDocument:, even if the document doesn’t exist. That seems like a mistake.

As a workaround you can test for self.document.currentRevisionID == nil.

—Jens

Brendan Duddridge

unread,
Jul 21, 2015, 1:58:17 PM7/21/15
to mobile-c...@googlegroups.com
Ah ok. Great. I'll do that.

Thanks Jens!

Brendan
Reply all
Reply to author
Forward
0 new messages