Niazipan Niazipan - 3 months ago 17
iOS Question

iOS - Accessing viewControllers on storyboard from appDelegate

I've got an app using Core Data where I'm creating a managedObjectConext in the app delegate.

I want to pass that managedObjectConext to two view controllers on my storyboard so their using the same managedObjectConext to save and fetch to and from.

I can access the first view controller with:

self.window.rootViewController


But the second view controller I want to access is then after a segue from the first and no reference is returned from it.

I tried:

instantiateViewControllerWithIdentifier:


But that creates a new instance of the view rather than allowing me to access the second view controller that appears after the segue.

So my question is, how can I access the second view controller?

Or (as I'm very new to this) is there a better way to be managing/passing the data between the view controllers?

Thanks in advance.

lxt lxt
Answer

Or (as I'm very new to this) is there a better way to be managing/passing the data between the view controllers?

It depends on the data you're trying to pass around. In this case, you want to give your view controllers access to your Core Data managed object context. Because this is something you're going to need throughout the lifespan of your app it would be better to have your view controllers access it via your application delegate.

You can do this via [[UIApplication sharedApplication] delegate] - however, you may need to typecast it to avoid compiler warnings, or alternatively you might want to create a macro that returns the managed object context to save you time and make your code a little more readable.

If you told XCode you wanted to use Core Data when you created the project you should have the methods to retrieve your object context already in your app delegate. If not, you'll need to create them.

To create a macro to save you having to write out [[UIApplication sharedApplication] delegate] every time you need to access the managed object context, check out this answer: Short hand for [[UIApplication sharedApplication] delegate]?

Comments