【问题标题】:How should a virtual Core Data property be retained?应该如何保留虚拟核心数据属性?
【发布时间】:2013-01-08 01:11:24
【问题描述】:

我有一个 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

【问题讨论】:

    标签: objective-c core-data key-value-observing key-value-coding


    【解决方案1】:

    这可能很简单:

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

    你还必须:

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

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 2014-10-18
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 2012-08-01
      相关资源
      最近更新 更多