缓存NSMangagedObject实例是一个坏主意吗?

sep*_*err 2 caching core-data nsmanagedobject ios7

我有一个名为Product的核心数据实体,最初在用户首次登录应用程序时填充.如果用户请求刷新,则可以再次加载它.

在应用程序的多个位置查询Product实体.所以,我决定实现一个可以在应用程序中共享的简单缓存.缓存将Product NSManagedObjects保存在地图中.这是一个坏主意吗?

ProductCache类:

@interface ProductCache ()
@end

@implementation ProductCache {

}
static NSDictionary *productsDictionary = nil;
static ProductCache *sharedInstance;

+ (ProductCache *)sharedInstance {
    @synchronized (self) {
        if (sharedInstance == nil) {
            sharedInstance = [[self alloc] init];
            [sharedInstance reload];
        }
    }
    return sharedInstance;
}

- (void) reload{
    NSMutableDictionary *productsMap = [[NSMutableDictionary alloc] init];
    CIAppDelegate *delegate = (CIAppDelegate *) [UIApplication sharedApplication].delegate;
    NSManagedObjectContext *managedObjectContext = delegate.managedObjectContext;
    NSArray *allProducts = [CoreDataManager getProducts:managedObjectContext];
    for (Product *product in allProducts) {
        [productsMap setObject:product forKey:product.productId];
    }
    productsDictionary = productsMap;
}

- (NSArray *)allProducts{
    return [productsDictionary allValues];
}

- (Product *) productForId:(NSNumber *)productId {
    return productId ? [productsDictionary objectForKey:productId] : nil;
}



@end
Run Code Online (Sandbox Code Playgroud)

Mar*_*rra 7

就个人而言,我不会像这样缓存Core Data对象.核心数据是您的缓存.当您还考虑到线程问题(NSManagedObject实例无法跨越线程边界)时,将内存缓存放在Core Data之上会变得更加危险.这甚至不考虑内存问题,在所有条件相同的情况下,您的缓存不会像Apple的缓存(即核心数据)那样执行.

如果您需要对Core Data对象进行即时访问(相对于磁盘上的纳秒访问),请考虑将磁盘缓存复制到内存缓存中,然后再访问它.但是,如果纳秒访问时间足够,请将其保留在Core Data中,并在需要时获取实体.如果您发现重复但是不在顶部放置缓存,则为获取构建便捷方法.