Does NSStringFromClass([MyEntityClass class]) generate a safe Core Data Entity name?

后端 未结 1 799
刺人心
刺人心 2021-01-04 14:17

Most (all I\'ve seen) Core Data tutorials use the following code snippet with @\"MyEntityClass\" hard-coded in:

NSFetchRequest *request = [[NSFe         


        
相关标签:
1条回答
  • 2021-01-04 14:50

    Yes, that code is fine, if your entity's class is set to MyEntityClass in your model.

    I prefer to give the entity class a class method that returns the entity name:

    + (NSString *)entityName {
        return NSStringFromClass(self);
    }
    

    and call it like this:

    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:[MyEntityClass entityName]];
    

    This way, if I want to change the class name without changing the entity name in the model, I can just make the change in the class method:

    + (NSString *)entityName {
        return @"NewEntityName";
    }
    

    Why would I do that? Well, I might decide on a better name for the entity. Changing the class name doesn't break compatibility with an existing Core Data persistent store, but changing the entity name in the model file does. I can change the class name, and the entityName method, but leave the entity name unchanged in the model, and then I don't have to worry about migration. (Lightweight migration supports renamed entities so it's not that big of a deal either way.)

    You could go further and actually have the entityName method look up the entity name from the managed object model at runtime. Suppose your application delegate has a message that returns the managed object model:

    + (NSString *)entityName {
        static NSString *name;
        static dispatch_once_t once;
        dispatch_once(&once, ^{
            NSString *myName = NSStringFromClass(self);
            NSManagedObjectModel *model = [(AppDelegate *)[UIApplication delegate] managedObjectModel];
            for (NSEntityDescription *description in model.entities) {
                if ([description.managedObjectClassName isEqualToString:myName]) {
                    name = description.name;
                    break;
                }
            }
            [NSException raise:NSInvalidArgumentException
                format:@"no entity found that uses %@ as its class", myName];
        });
        return name;
    }
    

    Obviously, if you really want to do this, you should factor out the contents of the dispatch_once block into a helper method, probably on your app delegate (or wherever you get the model).

    0 讨论(0)
提交回复
热议问题