計算にコストがかかる仮想プロパティを持つ NSManagedObject サブクラスがあります。プロパティは、エンティティの具体的な属性の 1 つの値に依存します。パフォーマンス上の理由から、仮想プロパティが依存するプロパティが変更されたときにのみ、仮想プロパティの値を計算したいと考えています。
値がアクセスされるたびに、仮想プロパティのアクセサー (高価なもの) が呼び出されることに気付きました。仮想プロパティの計算値を保持する最善の方法は何ですか? 計算された値をキャッシュできる 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