0

我有一個NSManagedObject子類,它的虛擬屬性計算起來很昂貴。該屬性取決於實體的具體屬性之一的值。出於性能方面的原因,我只想在虛擬屬性取決於變化的屬性時計算虛擬屬性的值。如何保留虛擬Core Data屬性?

我注意到我的虛擬財產的訪問者(昂貴的)每次訪問該值都會被調用。保留虛擬財產的計算價值的最佳方法是什麼?是否有一些內置 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

這可能是somethi NG簡單:

if (self.data) { 
    if(!_photos) { 
     _photos = [self.data expensiveCalculation]; 
    } 
    return _photos; 
} else { 
    return nil; 
} 

,你也不得不:

- (void)refresh 
{ 
    self.data = [self newData]; // not shown 
    _photos = nil; 
}