Load a previous model version

前端 未结 5 633
小蘑菇
小蘑菇 2021-02-12 19:31

I am loading a NSManagedObjectModel model with the initWithContentsOfURL: constructor like this:

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@\"MyDoc         


        
5条回答
  •  感动是毒
    2021-02-12 20:05

    Made the solution offered by @Schoob into a category, because they rock.

    @interface NSManagedObjectModel (version)
    + (NSManagedObjectModel *)modelFromBundle:(NSBundle *)bundle name:(NSString *)modelName version:(NSString *)version;
    @end
    
    @implementation NSManagedObjectModel (version)
    + (NSManagedObjectModel *)modelFromBundle:(NSBundle *)bundle name:(NSString *)modelName version:(NSString *)version
    {
        if(!bundle)
            bundle = [NSBundle mainBundle];
    
        NSString *resource = [[modelName stringByAppendingPathExtension:@"momd"] stringByAppendingPathComponent:version];
        NSURL *modelURL = [bundle URLForResource:resource withExtension:@"mom"];
        NSAssert(modelURL,@"Unable to find MOM - %@",resource);
        NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
        NSAssert(model,@"Unable to load MOM at URL- %@",modelURL);
        return model;
    }
    @end
    

提交回复
热议问题