Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

ios - Why doesn't NSManagedObject instances hold a strong reference to their NSManagedObjectContext?

As pointed out in another question on SO (and the Apple docs), NSManagedObject instances do not hold a strong reference to the NSManagedObjectContext from which they originated. On first blush, this seems like a strange decision, since NSManagedObject instances are nearly useless without their context, since it leads to confusing bugs such as faults not firing when they should.

Can anyone provide some background on why this is the case? Would it be dangerous to implement an NSManagedObject subclass that automatically holds a strong reference to its NSManagedObjectContext?

Edit: thanks to great answers to this question, I've discovered that my managed objects were created against an intentionally temporary NSManagedObjectContext by RestKit. This follows into my next question, specific to RestKit, here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It makes more sense for an NSManagedObjectContext to own its NSManagedObjects than the other way around.

Keep in mind that the context is like a draw pad with all its objects on it. If that context goes away, the objects are no longer valid. If the objects owned the context, then the context going away would do nothing to the objects and they still appeared to be valid. In other words: a context can exist without objects, objects can't exist without a context.

Of course, a hybrid model (where a context owns its objects and objects own their context) wouldn't work either, because then you would run into a retain cycle.

NSManagedObject instances are nearly useless without their context

They can be (though not necessarily), but remember that they do have a reference to their context! Presumably it's a weak reference, but a reference nonetheless. If that reference returns nil, the object is invalid. If you make sure your context stays around (which is what I did in my answer to the other question), you won't have any issues.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...