Search code examples
iosuiimageuitableviewnsdatasegue

In iOS how do you get an image from a sub ViewController?


I am trying to get an image from my sub ViewController and upload it to my server. Here is my code for the image.

StoryTableViewController *storyTable = [[StoryTableViewController alloc] init];
UIImage *storyImage = storyTable.storyPhotoPreview.image;

NSData *imageData =UIImageJPEGRepresentation(storyImage, 0.8);

I am importing the StoryTableViewController that is my sub ViewController in my h file. StoryTableViewController is an embeded segue. Thanks in advance for any answers you can give me.


Solution

  • The answer is don't do that. That breaks the encapsulation of the view controller. It also just plain doesn't work in cases like yours.

    You should treat another view controller's views as private.

    If you want to be able to get an image from another view controller, add a method that fetches the images and returns it.

    Alternately you could add a UIImage property to your StoryTableViewController and set up that property at init time.

    BTW, you should not create a view controller with alloc/init. The designated initializer for creating a view controller is initWithNibName:bundle:

    Note that for view controllers that get invoked inside a nib (unusual for view controllers, but not unheard-of) they will be created using initWithCoder, which is an exception to the rule that you should always call an object's designated initializer.

    If you're using storyboards then you should load your view controller using instantiateViewControllerWithIdentifier: