Or Ron
Or Ron

Reputation: 2343

Transient Attribute in CoreData

I'm trying to use the transient properties attribute in CoreData. Eventually, I'm trying to create an object that will be saved in memory only in runtime and not in the database.

My Setter and getter for the property:

-(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"];
}

I have problem with my new created object, at the beginning it was creating it from scratch every time and now it's just not working properly.

Can anyone advise on how to write proper setter and getter in order to create the object once in the first time and then used the same one every time im calling the getter ?

Thanks.

Upvotes: 2

Views: 543

Answers (1)

Damien Del Russo
Damien Del Russo

Reputation: 1048

Hmm I have a very basic understanding of Core Data, and I have worked with this problem. If you have a NSManagedObject subclass, you can't add instance variables via a category. You can add setters and getters and properties, but no additional storage.

That transient thing sounds kind of interesting. Another way to do it is to have a "regular" object (subclass of NSObject) that corresponds to your NSManagedObject, and also has whatever non-CoreData properties you want (including storage ivars). So it looks something like:

(Stock is a CoreData entity)

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

Good luck,

Damien

Upvotes: 0

Related Questions