我有一个带有虚拟属性的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
答案 0 :(得分:0)
这可能是一件简单的事情:
if (self.data) {
if(!_photos) {
_photos = [self.data expensiveCalculation];
}
return _photos;
} else {
return nil;
}
你还必须:
- (void)refresh
{
self.data = [self newData]; // not shown
_photos = nil;
}