我有一个 NSManagedObject 子类,它的虚拟属性计算起来很昂贵。该属性取决于实体的具体属性之一的值。出于性能原因,我只想在它所依赖的属性发生变化时计算虚拟属性的值。
我注意到每次访问值时都会调用我的虚拟财产的访问器(昂贵的访问器)。保留虚拟财产的计算价值的最佳方法是什么?是否有一些KVC 的内置部分允许我缓存计算的值?
界面:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface CDUserPhotos : NSManagedObject
// Core Data attribute
@property (nonatomic, retain) NSData * data;
// Virtual property
@property (readonly) NSArray* photos;
// Changes the value of 'data' property
- (void)refresh;
@end
执行:
#import "CDUserPhotos.h"
@implementation CDUserPhotos
// Core data attributes
@dynamic data;
#pragma mark -
#pragma mark Public
+ (NSSet *)keyPathsForValuesAffectingPhotos
{
NSSet* set = [NSMutableSet setWithObjects:@"data", nil];
return set;
}
#pragma mark -
- (NSArray *)photos
{
if ( self.data )
{
return [self.data expensiveCalculation]; // We want to prevent calls to this method!
}
return nil;
}
- (void)refresh
{
// some code deleted here. Basically, the value of self.data changes which therefore changes the value of self.photos.
self.data = [self newData]; // not shown
}
@end
其他一些代码
// self.albums.photos is an object of CDUserPhotos (NSManagedObject)
j = self.albums.photos.count; // triggers expensive calculation
k = self.albums.photos.count; // should not trigger expensive calculation
[self.albums refresh];
q = self.albums.photos.count; // triggers expensive calculation