Why use delegates at all? [closed] - ios

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have some questions about delegates in Objective-C:
What's the point of using them at all? Why i can't just create class with all methods, that i need and then set object of this class as property (i.e. what's the convenience of using protocols)?
Who invokes the methods of AppDelegate? Why there is a class for these methods, not a protocol?
I read, that delegate methods contains words like "did", "will", "should", "become". So why the methods of ViewController named that way? How it is correlating with delegates?

What's the point of using them at all? Why i can't just create class with all methods, that i need and then set object of this class as property (i.e. what's the convenience of using protocols)?
A single object can conform to multiple protocols, for example it could be both a UITableViewDelegate and a UIAlertViewDelegate. A single class cannot have multiple superclasses (even in languages where this is syntactically legal, we have long known that this creates significant problems, most famously the Diamond Problem).
Who invokes the methods of AppDelegate? Why there is a class for these methods, not a protocol?
The UIApplication invokes the methods. It is a protocol: UIApplicationDelegate. There just happens to be a class that conforms to that protocol.
I read, that delegate methods contains words like "did", "will", "should", "become". So why the methods of ViewController named that way? How it is correlating with delegates?
UIViewController is not a delegate, nor does it have a delegate (well, a transitioning delegate was added in iOS 7, but that doesn't change much). It is a class that is designed to be subclassed. These are methods that are intended to be overridden if you want to know when various events occur. That have similar names because they are called for similar reasons.

A delegate is basically a listener for events that happen in another class. To highlight the usefulness of delegates, think about the AppDelegate file, which is a listener for high level system events, such as when the app terminates or when it enters the background. It allows you to specify a common policy for something that could happen "anywhere" in your program and "anytime" during execution. It gives you a greater sense of control.

Related

Is setting singleton to nil a good policy or it should never be set to nil? [iOS, Swift] [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I know we should completely avoid singleton, as its difficult to test them in unit testing.
Let assume someone has written a code for singleton and i have been assigned task to write unit tests for it.
Is setting singleton to nil a good policy or it should never be set to nil?
If setting to them is nil policy then,
should i make it an optional or should i crate a private setter and public getter, then later on write reset() function to make singleton nil ?
Why I want to set to nil to perform unit test on singleton class.
ok, i would like to extend this question. assuminng that its not good practise to set singleton nil. Another query in mind is, suppose someone has already written code for singleton class.
now they have assigned task to you to test that singleton class. (not the other class which uses them).
how to work on that ? as for SUT, we mostly alloc SUT in setup() method and set to nil in teardown() method.
but since it is singleton , we can not set to nil, and also in setup() me can't alloc it, we can refer to same object again and again.
First thing Singleton class should never be nil. As it's name says we are allocating memory for singleton class only once.
You Can't 'deinit' singleton class if you want to test you can do it like creating methods.
e.g if your singleton class is for like NotificationManager then create two methods subscribeForNotification() & unsubscribeForNotification() You can init or deinit object available in singleton class but not deinit singleton class.

Why do the methods of a delegate couldn't be implemented in the main class firstly? [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have some questions about delegates in Objective-C:
What's the point of using them at all? Why i can't just create class with all methods, that i need and then set object of this class as property (i.e. what's the convenience of using protocols)?
Who invokes the methods of AppDelegate? Why there is a class for these methods, not a protocol?
I read, that delegate methods contains words like "did", "will", "should", "become". So why the methods of ViewController named that way? How it is correlating with delegates?
What's the point of using them at all? Why i can't just create class with all methods, that i need and then set object of this class as property (i.e. what's the convenience of using protocols)?
A single object can conform to multiple protocols, for example it could be both a UITableViewDelegate and a UIAlertViewDelegate. A single class cannot have multiple superclasses (even in languages where this is syntactically legal, we have long known that this creates significant problems, most famously the Diamond Problem).
Who invokes the methods of AppDelegate? Why there is a class for these methods, not a protocol?
The UIApplication invokes the methods. It is a protocol: UIApplicationDelegate. There just happens to be a class that conforms to that protocol.
I read, that delegate methods contains words like "did", "will", "should", "become". So why the methods of ViewController named that way? How it is correlating with delegates?
UIViewController is not a delegate, nor does it have a delegate (well, a transitioning delegate was added in iOS 7, but that doesn't change much). It is a class that is designed to be subclassed. These are methods that are intended to be overridden if you want to know when various events occur. That have similar names because they are called for similar reasons.
A delegate is basically a listener for events that happen in another class. To highlight the usefulness of delegates, think about the AppDelegate file, which is a listener for high level system events, such as when the app terminates or when it enters the background. It allows you to specify a common policy for something that could happen "anywhere" in your program and "anytime" during execution. It gives you a greater sense of control.

Need help in iOS app's architecture. Use Singletons or not? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have a class ServiceClass, a closure function in this class eg LoginViaEmail, calls APILayer. APILayer calls HttpLayer and JSONHandler and returns output to ServiceClass. ServiceClass further returns some info to ViewController when completionblock is received.
My questions are
Shall I make ServiceClass as Singleton? But then everybody says that they are anti-pattern and not a good approach.
If they are so bad, why does Apple use them? eg NSFileManager, NSWorkspace, UIApplication etc,
If not Singleton, then what shall I use? Make instance of ServiceClass every time I use it? Wouldn't that take too much memory?
Don't use a bunch of singletons if you want to write effective, independent and uncoupled, tests. If you don't care about tests, then singletons are fine.
Here's a half-way-house architecture that I use:
Have an overall App or Container class that owns all the services, and creates them, and injects them into each other as needed (so your services have all dependencies as properties, and don't access any statics)
Have your UIAppDelegate class own the single instance of the Container. This is the only 'singleton' in the app.
UIViewControllers etc get references to the Container, and its services through the UIAppDelegate, at viewDidLoad time, and save them into local properties. Eg they inject themselves. It would be nice to make this automatic.
Tests can set up and tear down the Container, or individual services as needed, knowing that other tests can't effect them.
If your ServiceClass doesn't need some sort of state inside, i would use class func inside and call it like that:
ServiceClass.fetchSomething { fetchedData in
self.updateUI(with: fetchedData)
}
You can use singleton class for this but if you do so then you should manage any network handler queue like functionality also.
Because network requests should be in asynchronous manner with concurrency support.
At any point of time in application, you may need to perform multiple request at once.
Using singleton pattern, this task will be little bit more complex and will need more management of multiple requests.
So if this is not an issue, then you can easily use singleton pattern.
Otherwise you can create a category of NSObject. This category will initiate the request send it to other request handling, parsing classes and then callBack response to sender.
Using category of NSObject, you will have benefit that you can initiate request from any class (as model, controller of any other helper class).
For example as I have used:
self.startPostRequest(withInput: payload,
requestApi: kApiScheduleList,
httpMethod: kHttpMethodPost,
headerDict: nil,
success: { (response) in
}, failure: { (error) in
})
Hope this will help.
If you need to discuss on any point, then let me know.

I need to understand why delegation in Objective-C is so important, what makes it so special?

So I've read about delegate explanation and practices a lot, but I still seem to not get it, I have specific questions and I would love to have some insightful simple answers.
Why use delegate over instance method? In UIAlertView why not just make – alertView:clickedButtonAtIndex: an instance method that will be called on my UIAlertView instance?
What is the delegate property? why do I have to make delegate property and define it with that weird syntax #property (nonatomic, strong) id <ClassesDelegate> delegate
Is delegate and protocol are two faces for a coin?
When do I know I should implement delegate in my app instead of direct calling?
Is delegate used as much and as important in Swift?
What gets called first and why? The method in the class who made himself a delegate? or the delegate method itself in class where it is declared?
Thank you for taking the time to go through this, I am desperately looking for a clear and helpful answers to my questions, feel free to give example or cover some related topic!
The advantage of delegation is Dependency Inversion.
Usually code has a compile-time dependency in the same direction of the run-time calling dependency. If this was the case the UITableview class would have a compile-time dependence on our code since it calls our code. By using delegation this is inverted, our code has a compile-time dependency on the UITableview class but the UITableview class calls our code at run-time.
There is a cost involved: we need to set the delegate and UITableview has to check at run-time that the delegate method is implemented.
Note: When I say UITableview I am including UITableviewDelegate and UITableviewDatasource.
See: Dependency inversion principle and Clean Code, Episode 13.
Maybe a real life example can better describe what's different in the delegation design pattern.
Suppose you open a new business, and you have an accountant to take care of the bureaucratic stuffs.
Scenario #1
You go to his office, and give him the information he needs:
the company name
the company # number/id
the number of employees
the email address
the street address
etc.
Then the accountant will store the data somewhere, and will probably tell you "don't forget to call me if there's any change".
Tomorrow you hire a new employee, but forget to notify your accountant. He will still use the original outdated data you provided him.
Scenario #2
Using the delegation pattern, you go to your accountant, and you provide him your phone number (the delegate), and nothing else.
Later, he'll call you, asking: what's the business name?
Later, he'll call you, asking: how many employees do you have?
Later, he'll call you, asking: what's your company address?
The day after you hire a new employee.
2 days later, he'll call you asking: how many employee do you have?
In the delegation model (scenario #2), you see that your accountant will always have on demand up-to-date data, because he will call you every time he needs data. That's what "don't call me, I'll call you" means when talking of inversion of control (from the accountant perspective).
Transposing that in development, for example to populate a table you have 2 options:
instantiate a table control, pass all the data (list of items to display), then ask the table to render itself
instantiate a table control, give it a pointer to a delegate, and let it call the delegate when it needs to know:
the number of rows in the table
the data to display on row no. n
the height the row no. n should have
etc.
but also when:
the row no. n has been tapped
the header has been tapped
etc.
Firstly, don't feel bad that all if stuff isn't clear yet. This is a good example of something that seems tricky at first, but just takes time really click. That will happen before you know it :-). I'll try and answer each of your points above:
1) Think of it this way - the way UIAlertView works now, it allows Apple to “delegate” the implementation of the alertView:clickedButtonAtIndex: to you. If this was an instance method of UIAlertView, it would be the same implementation for everyone. To customize the implementation would then require subclassing - an often over relied upon design pattern. Apple tends to go with composition over inheritance in their frameworks and this is an example of that. You can read more on that concept here: http://en.wikipedia.org/wiki/Composition_over_inheritance
2) The delegate property is a reference to the object which implements the delegation methods and whichs should be used to “delegate” those tasks to. The weird syntax just means this - a property that holds a reference to an object that adheres to the protocol.
3) Not quite - delegation leverages protocols as a means for it’s implementation. In the example above, the is this the name of a protocol that an object which can be considered a delegate for that class must adhere to. It is inside that protocol that the methods for which a delegate of that class must implement are defined. You can also have optional protocol methods but that’s a different topic.
4) If I understand the question correctly, I think a good sign that you may want a delegate to be implemented instead of simply adding instance methods to your object is when you think that you may want the implementation of those methods to be easily swapped out or changed. When the implementation of those methods changes considerably based on where/how the functionality your building is being used
5) Absolutely! Objective-C and Swift are programming languages and the delegation pattern is an example of a design pattern. In general design patterns are hoziontal concepts that transcend across the verticals of programming languages.
6) I’m not sure I understand you exactly but I think there’s a bit of misunderstanding in the question - the method does not get called twice. The method declared in the delegate protocol is called once - typically from the class that contains the delegate property. The class calls the delegates implementation of that property via something like:
[self.delegate someMethodThatMyDelegateImplemented];
I hope some of this helped!
Sometimes you want your UIAlertView to work different in different contexts. If you set your custom UIAlertView to be delegate of itself it has to provide all those contexts (a lot of if/else statements). You can also set seperate delegate for each context.
This way you say to your compiler that every class (id) which implements protocol ClassesDelegate can be set to this property. As a side note it should usually be weak instead of strong to not introduce reference cycle (class A holds B, and B holds A)
Protocol (interface in other languages) is used to define set of methods which should be implemented by class. If class conforms to the protocol you can call this methods without knowledge of the specific class. Delegate is pattern in which class A delegates some work to class B (e.g. abstract printer delegates his work real printer)
When you need few different behaviours which depends on context (e.g. ContactsViewController needs to refresh his list when download is finished, but SingleContactViewController needs to reload image, labels etc.)
It is one of the most fundamental patterns in programming, so yes.
It's the same method
You can't just add a method to UIAlertView, because you don't have the source code. You'd have to subclass UIAlertView. But since you have more than one use of UIAlertView, You'd need several subclasses. That's very inconvenient.
Now let's say you use a library that subclasses UIAlertView, giving more functionality. That's trouble, because now you need to subclass this subclass instead of UIAlertView.
Now let's say that library uses different subclasses of UIAlertview, depending on whether you run on iOS 7 or 8, and UIAlertview unchanged on iOS 6. You're in trouble. Your subclassing pattern breaks down.
Instead, you create a delegate doing all the things specific to one UIAlertview. That delegate will work with the library just fine. Instead of subclassing a huge and complicated class, you write a very simple class. Most likely the code using the UIAlertview knows exactly what the delegate should be doing, so you can keep that code together.

Somes questions about Objective-C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm a student in a internship, and i'm learning Objective-C in order to develop an IOS application. They already had an existing base of code, but some part of the code give me problems.
As the previous developer isn't in the company anymore, and because no one else know about Objective-C, no one can answer some of my questions about how the application is built, so I can't determine if it is that i don't understand, or if it's just bad practices.
Here are these questions :
1°) In some classes, i found code like this :
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated] }
This code is useless, right ?
2°) In like 9/10 methods in the project, they return (void). Is it a common pratice in Obj-C (because everything is a pointer) ?
3°) Sometimes there is the interface declaration in both header and messages files. I guess it's because you want to declare only a part in header for a future include, and to have a "private" part. But in a file, i find the following code :
In header :
#interface WebViewController : UIViewController
#properties ...
#end
In Msg file :
#import ...
#interface WebViewController ()
#end
#implementation WebViewController ...
What's the point declaring a void interface a second time in the msg file ?
4°) More, in another class, the interface is declared a second time too, but a method is defined (in the msg file). What's the point as the method is defined bellow, and is not declared in the header file ?
thank you in advance
Welcome to Objective-C :)
Not necessarily. The super class may have specific behaviour defined in it's own method implementation that would cause an issue if you didn't call it. Overriding methods means the super classes own method won't be called by default.
Added from comment: Of courser if you didn't override it then the superclass definition would get called just fine. There are 2 common reasons why you would find it overridden:
a. It's in the Xcode template so it has always been there and not been removed
b.it used to have other content but it was deleted and the method call left behind.
Yes. Although you don't explicitly return void in the method, you do need to specify some return type. If you're not returning anything then void is the right value. It's found commonly in obj-c classes as the method may respond to being called by mutating an internal ivar or property and not require a return. Alternatively the result might be to send a notification so a return value is not needed. Increasingly the use of block-based completion handlers replaces explicit value return as a way to respond to the contents of a method.
Yes, it's to give a private interface that you don't want exposed. In the case where there's nothing in the private interface it's probably there because it came with the template code from Xcode and no one removed it. You can ignore or remove.
For the one you mention with a method, while it's not required to declare private methods in an interface it makes sense from the point of view of writing readable code (a strongly endorsed concept in obj-c). Since the compiler will remove any unnecessary code it makes no difference to declare it and makes the task of reading the code and understanding the class that much easier when you or someone else returns to it later. It's a also a good place to put documentation in comments as it groups it all together.
Hope that helps. Check out the Objective-C programming guides from Apple to for more best practice tips.
1). Yes you can delete this method
2). It depends upon your requirement, whether you want a return type or not. e.g.
- (BOOL)isEmptyOrNull:(NSString*)str;
3). These are called extensions, you can read more about it here http://rypress.com/tutorials/objective-c/categories.html
Extensions are used to hide the methods from out side world(by saying hide I mean you can't find those methods with your eyes)
4). Methods define in implementation file are not visible to a programmer, it's just like private methods in java but in ObjC there is no such thing like private method. Read this thread for private methods Best way to define private methods for a class in Objective-C

Resources