Why declare in .h when setting a UI object delegate to self? - ios

Whenever I create a UI object such as UITextField programmatically, I do this:
txt.delegate = self;
A compiler warning appears and asks me to add UITextFieldDelegate in the .h file.
I noticed though that it makes no difference with or without, the code works fine either way.
But the compiler warning disappears. Why is this?

You don't actually need to set the delegate property on your objects unless you are actually using the delegate methods. For example, if you need to know when the UITextField is about to begin editing. If you don't need to know when these things occur, you don't need to set the delegate.
Looking at it the other way, if you make your class conform to a delegate method (by adding <SomeClassDelegate> in the .h file), and then forget to implement required delegate methods, you'll get a warning from the compiler, and a crash when the app runs (and sends a required delegate message to your object).
To answer your question about not adding UITextFieldDelegate to your .h file, imagine your friend is looking for a French translator. You find a foreign looking man and introduce him. Your friend asks "But can he speak French?" You reply "I don't know". This is your warning.

Related

How does self.textField.delegate = self work in swift?

I am working with keyboard resign features in iPhone app development. I would like to know why
self.textField.delegate = self
needs to be included into the viewDidLoad of a viewController. I have tried to find reasons of this but no explanation has been clear so far.
A few points
The reason you need to set the delegate is because without it the view doesn't know about the view controller. So it wouldn't know about your method textFieldDidEndEditing and it would never be called.
That is the basic premise of delegate, you are telling that object, "here is an object that I want you to call methods on"
It doesn't have to be set in viewDidLoad - but it's often the most convient place to set up delegates for views.
The delegate doesn't have to be the view controller (self), in your case it's the simplest way, but with a UITableView its common to have another class be the delegate so that all the logic isn't in one place and so it can be changed.
The UITextFieldDelegate protocol defines methods that you use to manage the editing and validation of text in a UITextField object. All of the methods of this protocol are optional.
A text field calls the methods of its delegate in response to important changes. You use these methods to validate text that was typed by the user, to respond to specific interactions with the keyboard, and to control the overall editing process. Editing begins shortly before the text field becomes the first responder and displays the keyboard (or its assigned input view).
From more info. check apple doc.
Its not necessary to use self.textField.delegate = self if you don't want to manage the editing and validation of text in a UITextField object as all the methods of UITextFieldDelegate is optional.
For your other questions like what does .delegate = self do??
When you "set the delegate," what you are doing is saying where you want the messages to go.
Hence,
blah.delegate = amazingPlace will send the messages to "amazingPlace".
blah.delegate = somewhereElse will send the messages to "somewhereElse".
blah.delegate = self will send the messages to you.
... check this source link for details
Delegates are key concepts in iOS development so I'd suggest taking a good look at the documentation for them. It can be particularly useful to create your own custom delegates in certain situations too so understanding and using them in the right places can really help improve the structure of your projects.
There are a couple of key reasons for using them. Firstly, they allow safe communication between classes. In your example, the textField object that you're using is communicating back to your view controller. This is why you need to set your view controller as its delegate. Otherwise the text field doesn't have a delegate object (your view controller) to communicate with. The text field fires certain methods at certain times, such as textFieldDidBeginEditing, and calls these on its delegate object if it has one. When you register your view controller as the text view's delegate you can tap into these callbacks.
The other benefit is that delegates allow you to separate concerns and encapsulate or abstract responsibilities. It might be that the main concern for the text view is how to handle text in its view but not necessarily what to do when has been entered, or when the return button in the keyboard is pressed, or how to validate text that has been input. It's better that these tasks are handed over to something else, such as a delegate (in Obj-C parlance), and that is why in your example you have to register one class as the delegate for another.
As stated before, UITextfield delegation allows you to control events on your textfield.
You ll have the ability to edit functions like
textFieldShoulEndEditing
or
textFieldDidEndEditing
in order to add custom rules, for example : text validation.
Take a look at Apple doc.
If you don't need it, you can delete this line and UITextfieldDelegate on your class declaration.
You need to either set the delegate of a UITextField in code with self.textField.delegate = self
or make your viewcontroller (or any other class) a delegate with class MyViewController: UITextFieldDelegate and set the delegate of the UITextField in the storyboard by control dragging from the textfield to the viewController.

Get UITextView text without delegate

I have tried to make a location autocomplete text view class by subclassing UITextField and use Google Place Autocomplete API. This works great, but I have a design error due to the implementation. To observe when the user types text, I set the UITextFieldDelegate to self in the custom subclass and track changes to the typed text in textView:shouldChangeTextInRange:replacementText:. This works, but here is the design error: If someone now wants to check what is typed into the custom subclass by setting the delegate to something new, the delegate of my class is not set to the object of the class itself anymore. Now the custom class is useless. Is there any way to either get the text as it is typed without the delegate, prevent the delegate from being changed, or in any other way fix my problem?
A few options I have though about that could work, but in a bad way:
Check regularly what the text property is: Should be obvious why busy waiting is a stupid idea
Override the delegate property and set it to private: Not sure if this will even work, but if it did, the class is no longer a proper subclass of UITextField and all delegate methods are unavailable when implementing my subclass.
Provide a new delegate for further use of the delegate: Allows someone to get the same things as the UITextFieldDelegate provides, but it still messes up the documentation and proper implementation of UITextField
Delegates in UIKit I normally one to one connections. Which can cause the problem you have described.
If you want multiple delegates of a UITextField I would derive a class from UITextField for example MYTextField and add a method to addDelegate and removeDelegate that maintains a list of delegates. The sent the MYTextField's delegate to itself and broadcast any delegate method to all listeners in the delegate array.
this post shows example code on how do maintain a list of multiple delegates.
Delegation to multiple objects

Objective C UIViewController subclass?

Recently I've been looking into RESideMenu. What really piqued my interest was his 'UIViewController+RESideMenu.h/m'. It appears to me that this is a way to subclass a UIViewController. It includes IBActions and methods in it that are accessible from anything that inherits from UIViewController.
All of my attempts to replicate this have failed. Is there a special way to go about it?
Usually that sort of classname is used to denote a category. Instead of subclassing it adds additional methods and properties to a class. For more information see here: CustomizingExistingClasses

Weak Event Pattern in MonoTouch

I used to develop iOS apps using the Objective-C language, and relied on the dealloc method to perform some cleanup/unregister tasks in my application. Now on the MonoTouch (garbage collected) it is not an option anymore.
Suppose I have a UIViewController that adds as a subview of it's View property an instance of MyView (UIView subclass). MyView in turn registers itself to receive some events from another manager/global object so that it knows how to update itself accordingly (e.g.: onlineProfilesManager.Refreshed += () => <update UI with the new state>;).
As long as MyView is on screen, everything is fine. However I must know when it's removed from the screen so that I can unregister MyView from the event handler.
In Obj-C this could be simply done in the dealloc method because when the screen changes the UIViewController is deallocated --> MyView is removed from it's superview and then MyView dealloc method is called.
In Monotouch I don't have this 'deterministic' flow anymore. I tried to put some print statements in the UIViewController and MyView destructors but they are never called (the reason is because the MyView is still registered for the event handler, since I don't know when/how to unregister it, it will never be deallocated).
Does anyone know what is the 'pattern' to handle such situations in MonoTouch? I think I'm missing a fundamental concept and getting into trouble developing my apps.
Thanks in advance.
EDIT
I'm editing my question because looks like the solution for my problem is using the Weak Event Pattern but I didn't find an implementation for the MonoTouch platform.
Does anyone know how can I use the Weak Event Pattern in MonoTouch ?
The best way to handle events is to unregister them in ViewWillDisappear and register them in ViewWillAppear. This means that you can't use anonymous methods though as you don't have a reference to the method to unregister it.
If that doesn't suit what you need, you can do something similar to this http://sgmunn.com/blog/2012/05/non-gcd-event-handlers/
Cheers.
If you are looking for weak events, you can try my "Messenger" implementation here.
It is inspired by what is available in TinyIoC, but I re-implemented it so it used less reflection, etc.

Calling the delegate methods

Still I couldn't understand completely how these delegate methods are getting called.
I have UIViewController,UITextFieldDelegate in one class which will call its delegate methods without specifying like textField.delegate = self;
But for some different purposes like UIWebViewDelegate we are supposed to enter like webView.delegate = self; and it seems like it is calling its delegate methods. Perfect.
But now I am facing a problem. I am using CLLocationManagerDelegate and also CALayer in same class. For both I am giving location.delegate =self; and layer.delegate =self; At some point both are conflicting each other and only one of the thing is working either CLLocationManagerDelegate or CALayer. The other thing is getting stopped. I don't why it so happens like this? Any reason? How can we overcome this. Even I planned to use some other frameWork, say UIWebView . I will face same problem for those delegate methods also. Can you tell me why it is working in that way ?
The classes that will call its delegates without you specifying them have default implementations, which means that they already know what to do, and will only change their behavior if you override these methods.
Setting 2 or more classes to the same delegate should not interfere with each other (unless for a very weird reason in where the method is named the same in both custom classes).
Your problem is most likely the fact that you havent implemented those methods or are using those classes wrong.
For example, Location manager requires you to create an instance, configure it and START running updates. The most common method for a delegate of this type is the "did update location" (or something like that). Which you have to implement if you want to be informed of every time a new location is received. Otherwise you have to read the location manually whenever you desire.
As a suggestion, every time you set a delegate for an object, you have to do the object.delegate = self; thing. And you probably noticed that you will get a warning until you specify in the header that it conforms to that protocol: for example.
Just control click the UITextFieldDelegate word.
Look for the methods under #required, THOSE you have to always implement. the #optional have default implementations so unless you wanna change the behavior its not needed to implement them.

Resources