【问题标题】:Transient Attribute in CoreDataCoreData 中的瞬态属性
【发布时间】:2012-02-29 10:33:25
【问题描述】:

我正在尝试使用 CoreData 中的瞬态属性属性。最后,我尝试创建一个对象,该对象仅在运行时保存在内存中,而不是在数据库中。

我的属性的 Setter 和 getter:

-(AVMutableComposition *) composition
{
    AVMutableComposition *composition;
    [self willAccessValueForKey:@"composition"];
    composition = [self primitiveValueForKey:@"composition"];
    [self didAccessValueForKey:@"composition"];
    if (composition == nil) 
    {
        self.composition = [AVMutableComposition composition];
    }

return composition;
}
- (void)setComposition:(AVMutableComposition*)aComposition
{
    [self willChangeValueForKey:@"composition"];
    [self setPrimitiveValue:aComposition forKey:@"composition"];
    [self didChangeValueForKey:@"composition"];
}

我的新创建对象有问题,一开始它每次都是从头开始创建它,现在它无法正常工作。

谁能建议如何编写正确的 setter 和 getter 以便第一次创建对象,然后每次调用 getter 时都使用相同的对象?

谢谢。

【问题讨论】:

    标签: iphone ios ipad core-data


    【解决方案1】:

    嗯,我对 Core Data 有非常基本的了解,并且我已经解决了这个问题。如果您有 NSManagedObject 子类,则不能通过类别添加实例变量。您可以添加 setter 和 getter 以及属性,但不能添加额外的存储空间。

    那种短暂的东西听起来很有趣。另一种方法是拥有一个与您的 NSManagedObject 相对应的“常规”对象(NSObject 的子类),并且还具有您想要的任何非 CoreData 属性(包括存储 ivars)。所以它看起来像:

    (Stock 是 CoreData 实体)

    ComboClass.h:

    #import <Foundation/Foundation.h>
    #import "Stock.h"
    
    @interface ComboClass : NSObject
    
    @property (weak, nonatomic) Stock *stock;
    @property (strong, nonatomic)  NSDictionary *nonPersistentDictionary;
    
    @end
    

    ComboClass.m:

    #import "ComboClass.h"
    
    @implementation ComboClass
    
    @synthesize stock = _stock;
    @synthesize nonPersistentDictionary = _nonPersistentDictionary;
    
    - (Stock*)stock {
        // retrieve the stock from CoreData using a fetchedResultsController
        return _stock;
    }
    
    - (NSDictionary*)nonPersistentDictionary {
        if (!_nonPersistentDictionary) {
            _nonPersistentDictionary = [[NSDictionary alloc] init];
        }
        return _nonPersistentDictionary;
    }
    
    @end
    

    祝你好运,

    达米安

    【讨论】:

      猜你喜欢
      • 2011-11-23
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 2011-02-10
      • 2012-02-25
      • 2011-07-20
      相关资源
      最近更新 更多