Calling functions from separate view controllers in swift - ios

I think the solution to this is going to need to use delegation, but I'm unfamiliar with how to use them.
So in my project, I have my main viewcontroller/storyboard that contains a UIScrollView. That UIScrollview calls another storyboard (xib file) as a subview. The other storyboard (which is an xib file) is controlled with another swift file.
My question is, when I call an action inside of my other storyboard, how can I call a function from the main viewcontroller. Like say the viewdidload from the first viewcontroller.
I can't make the whole thing a global function, it needs to stay inside its class. So if I try to do ViewController.viewDidLoad() it needs (I think) an instance variable or something.
Thanks.

You can try:
Using weak variable (property) in the other class with type UIViewController
Assign the parent view controller to that property after the other view is initialized
Good reads about weak, strong, unowned references Here And Here

Firstly, if you want to call it with class name as you said above declare your method with "class". So its just like static in Java. It makes it generic to call it anywhere in your project. Make a separate extension.
class func myfunc(){
}
if you want to send data from B to A controller. You use what is called delegation. You give the work of B to A. Make a protocol above B for functions that you want to do or send with them. Call them in B. And then in A write code for those functions. So that you have the data from B to A
Else you demand something like common data. Create a singleton class and initialize properties methods there. You can use objects for that and call it in other controller to modify or make different instances.
You dont call viewDidLoad(). As the name says it loads once. If you want something that modify everytime you screen appears, use viewWillAppear

Related

Swift 2 / XCode 7 - "EXC_BAD_ACCESS (code=2...)" when calling "ViewController().view" in another class

why is this error happening and what can i do to fix/prevent in the future? thanks!
NOTE: my other class is set up as such:
class Other {
//then all relevant funcs called
}
am i missing some basic setup information in order for this to run?
The formal explanation would be:
You're trying to access the view property before it was initialized. Another way to look at it is that you're trying to access the view property before it was loaded (in viewDidLoad).
Solution:
Depends what you're using that view for. I've never had to access another view controller's property like that. Consider exploring other strategies such as delegation, weak references to another controller, and passing variables in prepareForSegue if you need a reference from a view controller from another.

Not able to get the video if the stream is created first in OPENTOK

I am basically trying to implement a video conference functionality using opentok.
I have two view controllers.
Class A that has a grey image(to tell user is offline).
It calls setsession from class B to establish the session.
uses ClassADelegate and implements setUserOnlineImage that sets the class A grey image to green.
Class B holds a method useronline.
Has a class method sharedinstance that gives out the singleton instance of the class
viewdidload ->sets a variable type = 2;
setsession ->sets a variable type = 1;
It also has a protocol "ClassADelegate"
Protocol ClassADelegate has method setUserOnlineImage.
Has a callback method session:streamCreated: that is called when a subscriber is created and setupPublisher that publishes the video
The flow is like this.
first Class A calls the setsession from Class B to establish session.
Then when a connect button is clicked the viewdidload is called and then the setupPublisher is called, view is modified loaded and all that.
Now when a subscriber tries to connect session:streamCreated: is called. here when i try to print type value it comes as one, likewise many other variables also become nil which inturn results in just giving the audio and the video isnt seen.
where as if first session:streamCreated: is called (first video is received and then connect is clicked) the flow works fine and the print statement in session:streamCreated: correctly prints type value as 2.
Someone help me figure out whats happening.
I want to know why the type value is getting changed & various other variables become nil. This is preventing the video from showing. Am i missing something? Is any other instance is been taken(but I am using a singleton instance)?
The flow you describe doesn't follow any of the known patterns of how UIViewControllers should behave. Specifically, you shouldn't need to use a singleton instance of a view controller. I think you need to reconsider the architecture, specifically the relationship between these two view controllers.
By the way, the viewDidLoad method is called on the view controller as soon as its view property becomes available, which can be before its on the screen. If the view controller is loading its view from a storyboard or nib, viewDidLoad is called as soon as that view is ready. Otherwise if you are implementing loadView, viewDidLoad is called after that method is finished.
Can you describe what Class A and Class B are trying to accomplish? It sounds like Class A is a view controller for some type of status view that shows a user's online/offline status. Class B sounds like its the OTSessionDelegate as well as the view controller for where the publisher/subscriber views will be placed. Why are these not the same View Controller? (generally view controllers are meant to control a "screenful" of content, unless you are using View Controller Containment). If these two view controllers are not on the screen at the same time, can you use a segue to pass data between them when the transition occurs?
UPDATE:
The additional information is useful for me to give you a recommendation. The thing I'm still uncertain about is if you actually do have these 2 view controllers' views on screen at the same time. This solution should work in both cases.
Outside of a segue, one view controller should not really be calling another view controller's methods directly (so calling setsession as you described is a bad idea). You shouldn't even set one as the delegate of another. At most they should share a Model object to communicate. The OTSession can be seen as a Model object. The challenging limitation is that when using the delegation pattern, only one object (you chose Class B) can be informed of updates. Rather than using the delegation pattern, I think you should use NSNotifications. In order to accomplish this, you should "wrap" the OTSession model in your own model object, setting your own model object as the delegate. Then you can notify both controllers of interesting changes as they happen. I've created a diagram to demonstrate:
In this diagram, all the downward solid arrows are owning references. VideoConference would be your own class and it would implement the OTSessionDelegateProtocol. On initialization, the VideoConference instance would create and own an OTSession instance. When something happens that Class A or Class B need to know about (such as the remote user coming online), VideoConference can send an NSNotification, which both controllers can be observers. Here is a useful article about NSNotifications.

Who calls the private method during unwinding in Xcode?

For implementing unwind segue we need make control-drag in the storyboard and
create private method in the destination view controller.
I don't understand : if method is private, how it works? Because in the implementation file of my view controller this NOT calling.
When executed, your application parses the .storyboard file at first, getting to know what classes it needs to instantiate and other important information, like segue connections. Then, it creates class instances (and manages them later). Then, when requested (e.g. after a button press), it attempts to find a method unwindToList: in the controller instance. If there is one, it would execute. If not, an exception would be thrown.
However, that method is not exactly hidden. Basically, there is no such thing as a private method in Objective-C; at least not in the same way as some other languages have. Every method is accessible by the runtime. If you're interested in how Objective-C works exactly, take a look at these pages, for example:
How does objective-c handle method resolution at run-time?
http://cocoasamurai.blogspot.ru/2010/01/understanding-objective-c-runtime.html

how to pass data to the parent class in ios?

I am a beginner in objective-C. So please forgive if my question is silly.
In my root view controller A, I added a subview B.
In b there will be another subview C. C contains another subview D.
How can I call a method in A from D.
I know that we can use delegates for passing data to the parent controller.
But my question is that do i need to create delegate which calls C from D and another one for call B from C and so on?
Or is there any method which directly calls a method in A from D?
But my question is that do i need to create delegate which calls C from D and another one for call B from C and so on?
The view controller's job is to manage it's view and all of that view's subviews. If you've got a view that needs to send the view controller a message, like a control that needs to send a message somewhere when the user changes its value, then the view controller should be aware that it's there. In such a case, the view controller can take care of setting itself (or some other appropriate object) as said subview's delegate or target when the view hierarchy is loaded, like this:
- (void)viewDidLoad
{
self.needControl.delegate = self;
}
That way, the needy control doesn't need to know anything about the object that is its delegate. It's not assuming that the object is the view controller, or its parent view, or anything else. All it cares about is that it has a delegate, and that its delegate implements the necessary methods. And that, in turn, helps you keep your code more flexible and maintainable and maybe even reusable.
Do i need to create delegate which calls C from D and another one for call B from C and so on? No
You can use a single delegate to call a method in A from D. From your comments i came to know B,C,D are UIView's controlled your root view controller. So the job is easy you need to set a delegate as its root view controller upon creating each sub views.
1. View B is creating from the root view controller itself so viewB.delegate = self
2. View C is creating from the view B so viewC.delegate = self.delegate
3. Repeat same for view D also
Now all your views are controlled by your delegate rootViewController.
Finally This answer will help you to complete your task
You should structure your code so that class D does not know class A exists at all.
There are a few specific techniques that are common in iOS/Mac programming:
class D has a delegate property, and calls methods on it. Use this when only one object can receive the delegate method, particularly useful for things like a button asking if it should be enabled or disabled right now. Use interface builder to set the delegate of the view to your instance of class A.
class D should have a "target" property (type id) and an "action" property (type SEL), and it sends the action message/selector to the target object. useful for when a view has a specific single action that it triggers, such as when a button is pressed, or the user presses Enter in an text field. Use interface builder to set the target and action of the view to your instance of class A.
class D sends messages and metadata to [NSNotificationCenter defaultCenter], and class A tells the notification center that it wants to observe those notifications. Useful when potentially many objects need to be notified when something happened, such as when a text field receives or looses keyboard focus.
class D has a property or properties sends Key Value Observing notifications whenever it the value of the property changes. Class A would tell the Key Value Observing system that it wants to know whenever a specific property on class D changes. This is useful when you care specifically about some data, such as when the value of a text field changes.
All of these techniques are described in more detail here on stack overflow or in Apple's official documentation.
Class B and C also should not know that class A exists. Class A should be the one that knows how to find the other objects, unless you can use interface builder (the first two options allow that).
Add your A_viewCon.h file into your D_viewCon.h file
create object of A_viewCon and set #property and #synthesize as properly.
call method of A_viewCon in D_viewConwrite following code.
[self.objectOFA_viewCon performSelector:#selector(MethodNameOFA_viewCon) withObject:nil afterDelay:0];
U can register Class A to observe a NSNotification like ->
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;
and post NSNotifications from Object of class D like ->
- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
This way u do not need to keep a reference/delegate and still u can communicate between alive objects.

xcode using view in subclass

I am learning to program the iphone and I wanted to do some drawing. I followed some example code and subclassed the viewcontroller and it worked fine. Now as I wanted to expand the program I came upon a design question that I could use a little help on.
I subclass myviewcontroller with mynewview. If I have any code in the myviewcontroller how do I call or reference it in mynewview and vice versa? I am not sure if I am asking this right but I am trying to understand the relationship between the class and subclass.
Objective-C objects benefit from inheritance. All classes are subclasses of NSObject, therefore you can call init on any object. If you created a custom class and gave it a method doSomethingAwesome, you are free to then implement doSomethingAwesome in any subclass of your custom class. However, declaring a method in a subclass does not add that method to the superclass. As an aside, I rarely find myself subclass sing my own custom classes. I believe that it is encouraged to maintain what is called a shallow object hierarchy. Usually I subclass the stock cocoa classes, customize to my needs and if I need custom methods in more than one subclass I will declare a category on the superclass rather than relying on inheritance to provide my custom behavior
The messaging system in Objective-C is dynamic. Every object includes a struct with information that the runtime use for introspection. Here the runtime will find a list of methods the object is able to respond. So, let's say you message an instance like this:
[mynewview someMethod];
The runtime will first check the object information to trying to find some method that will be able to respond the message. If nothing is found, then will query the super class, and so on. In fact, the runtime is much more complex, and will give any object more opportunities to respond (that's the dynamic part. For instance, mynewview might not have any method called someMethod and yet, might be able to satisfy the call, but that's something you might not want to worry right now).
From a child class you can call the superclass implementation of a given method with the keyboard super, so if mynewview is a subclass of myviewcontroller you can call myviewcontroller implementation from mynewview with:
[super someMethod];
If someMethod is both present in myviewcontroller and in mynewview, the runtime will automatically only call the child implementation, you have to call the parent implementation (if you have to) from the child implementation.

Resources