Septiadi Agus
Septiadi Agus

Reputation: 1775

Should Reference to Core Data Object be Strong or Weak?

I couldn't think of core data refer to anything outside coredata. So there is no way there will be reference cycle. At most core data object points to another coredata objects.

however, I may be wrong.

Managedobjectcontext do not hold strong reference to core data.

Is there any guide here?

Upvotes: 3

Views: 808

Answers (2)

chikuba
chikuba

Reputation: 4357

I am currently also unsure whether or not references should be strong or weak. The previous guys stated that they should be strong, but then I found this on:

https://developer.apple.com/library/prerelease/watchos/documentation/Cocoa/Conceptual/CoreData/CoreDataandStoryboards.html#//apple_ref/doc/uid/TP40001075-CH10-SW1

In the example code, Apple does this:

@interface DetailViewController : UIViewController

@property (weak) AAAEmployeeMO *employee;

@end

What we tend to do is to have a strong reference to the primary key of the object, and then a weak property that does lazy initialization if the object is nil. Like this;

@interface MyVC : UIViewController

@property (nonatomic, strong) NSString *objectId; 
@property (nonatomic, weak) SomeObject *myCoolObject; 

@end 

@implementation MyVC 

- (SomeObject *)myCoolObject {
    if (_myCoolObject == nil) {
        _myCoolObject = [SomeObject MR_findFirstByAttribute:@"primaryKey" withValue:self.objectId];
    }
    return _myCoolObject; 
} 

I'm still not sure if this is the correct way of doing it though. Please correct me.

Upvotes: 1

Jeff
Jeff

Reputation: 4229

Is there any guide here?

Here is a link to Core Data Programming Guide: Object Lifetime Management.

It was updated on July 2014, so it may have new information not published when you asked this question.

By default, though, the references between a managed object and its context are weak. This means that in general you cannot rely on a context to ensure the longevity of a managed object instance, and you cannot rely on the existence of a managed object to ensure the longevity of a context. Put another way, just because you fetched an object doesn’t mean it will stay around.

The exception to this rule is that a managed object context maintains a strong reference to any changed

This means your references to NSManagedObject subclasses (Core Data objects) should be strong.

Upvotes: 1

Related Questions