我有一个名为 Product 的核心数据实体,它在用户首次登录应用程序时被初始填充。如果用户请求刷新,它可以再次加载。
Product 实体在应用程序的多个位置被查询。因此,我决定实现一个可以在整个应用程序中共享的简单缓存。缓存保留产品 NSManagedObjects 在 map 中。这是一个坏主意吗?
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
最佳答案
就我个人而言,我不会像这样缓存核心数据对象。核心数据是您的缓存。当您还考虑到线程问题(NSManagedObject
实例不能跨越线程边界)时,将内存缓存置于 Core Data 之上的风险更大。这甚至没有考虑内存问题,在所有条件相同的情况下,您的缓存不会像 Apple 的缓存(即 Core Data)那样执行。
如果您需要即时访问(相对于磁盘上的纳秒级访问)您的 Core Data 对象,请考虑将您的磁盘缓存复制到内存缓存中,然后访问它。但是,如果纳秒级访问时间足够,将其保留在 Core Data 中并在需要时获取实体。如果您发现它重复但不要在顶部放置缓存,请为提取构建便利方法。
关于caching - 缓存 NSManagedObject 实例是个坏主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20849752/