Custom Initializers and Read-Only Properties in Core Data

Before working with Objective-C and Core Data, I had to create classes that needed to be initialized using certain parameters that could not be changed after initialization (although they could be read).

With Core Data, I believe that I can create a custom init in my derived NSManagedObject class if it includes a way to insert an object into this context:

-(Cell*) initWithOwner:(CellList*)ownerCellList andLocation:(int)initLocation
{
    if (self = (Cell*) [NSEntityDescription insertNewObjectForEntityForName:@"Cell"
                        inManagedObjectContext:[ownerCellList managedObjectContext]])
    {
        self.location = [NSNumber numberWithInt:initLocation];
        self.owner = ownerCellList;
        [ownerCellList addCellListObject:self];
    }
    return self;
}

Normally, I would have a location variable, and the location property would be read-only (so it cannot be changed after initialization). Is there any way to get such a template using Core Data? Is there a better way that I don't think about?

Thanks!

+3
2

. NSManagedObject, . -[NSManagedObject awakeFromInsert] () -[NSManagedObject awakeFromFetch] (, ) .

Objective-C, . , , . @property(readonly), . location. , , , .

+1

, , , - . , :

-(Cell*) initWithOwner:(CellList*)ownerCellList andLocation:(int)initLocation
{
    NSManagedObjectContext *context = [ownerCellList managedObjectContext];
    NSManagedObjectModel *managedObjectModel =
            [[context persistentStoreCoordinator] managedObjectModel];
    NSEntityDescription *entity =
            [[managedObjectModel entitiesByName] objectForKey:@"Cell"];
    self = [self initWithEntity:entity inManagedObjectContext:context];
    if (self)
    {
        self.location = [NSNumber numberWithInt:initLocation];
        self.owner = ownerCellList;
        [ownerCellList addCellListObject:self];
    }
    return self;
}

NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext: , , entityName (@ "Cell" ) ( ownerCellList) NSManagedObject.

0

Source: https://habr.com/ru/post/1721699/


All Articles