Search code examples
iosswiftcore-datansmanagedobjectcontextinout

Use the inout keyword when passing an NSManagedObjectContext into a function?


I'm working on my first real Core Data application and have been able to successfully pass the pointer to my managedObjectContext instance throughout my application using segues. I've run into a question however as I am at a crossroad where I need to pass my managedObjectContext into a function.

Question

Since functions are pass-by-value by default, I'm assuming that I'd be making a copy of my managedObjectContext instance thus potentially defeating the purpose of passing the original pointer to my managedObjectContext instance.

Should I use the inout modifier to avoid creating copies of my managedObjectContext?


Solution

  • NSManagedObjectContext is a class, and therefore a reference type. Reference types do not need to be passed with inout to share the instance. The "value" that is passed for reference types is the pointer to them.

    One thing that was lost (IMO) in the transition from ObjC to Swift is that reference types no longer have any indicator. In ObjC, you could identify them by the * in their type. In Swift, you just have to know which are which.