Core Data (Mac) How to implement auto increment on an ID field

前端 未结 2 1607
没有蜡笔的小新
没有蜡笔的小新 2021-02-11 01:29

I was wondering if anyone can point me in the direction of how to set up auto increment on an attribute in a coredata entity. I know the indexed check box just makes the field i

2条回答
  •  难免孤独
    2021-02-11 02:09

    I'm not quite sure what the id does in your app, but my first observation is that all the entities in your data model have both a name and an id, so they should probably have an abstract super-entity to contain name and id. Other than that, you can retrieve the max id in a set like this:

    Category *cat = /* get a category  */;
    NSSet *parts = cat.parts;
    NSNumber *maxID = [parts valueForKeyPath:@"@max.id"];
    

    for the id's of a category you could perform a fetch request for all the categories and then use this technique on the array that is returned. I don't know if you want to keep the id's of each model object unique or you want id's to start with 0 for the first object added to each entity.

    To make sure a field is unique you can use managed object validation. this is described in the Core Data Programming Guide and in more detail in the Model Object Implementation Guide. Making sure that a name is unique would require you to test it against all the names in a validateName:error: method. making an abstract super entity will make this a lot easier. To do it you get all the names of objects in the abstract super entity and test them against the value to be validated.

    Edit: If you use the abstract super entity then you should get the max id of the objects in the abstract super entity if you want them to be unique. Also as someone else pointed out the objectID of a managed object is a unique identifier for it that will always be the same, but looking at the app I don't think that's really what you want, because they will be computer numbers rather than the friendlier results of incrementing the highest known id when a new object is created. Another thing you should set the objet id in awakeFromInsert so that it is only called when the object is created.

提交回复
热议问题