Why would I make an all-optional message protocol? - cocoa

I'm writing a Cocoa API for a project and the API takes a delegate. The protocol that I came up with declares all the methods as optional, but why would I do that instead of just documenting the delegate methods in a header file and taking a plain id as a parameter?

For the benefit of your users. If the object takes delegates conforming to some protocol and they pass something else in, the compiler can tell them. That isn't possible if you take an id and use a category as the delegate method interface.

Because having "all of these methods" optional isn't quite the same as permitting "anything you care to send".

It also produces code that is more usable in the IDE. For example if I'm looking at
#interface MyController : NSObject <FooBarDelegate> {
}
#end
I can command+double click in Xcode to jump to the definition of FooBarDelegate. With a category there's no formal declaration of intent to be a delegate.
Also, #required can be a problem for future plans with regard to backward binary compatibility and a new preferred method signature.

Related

What is the purpose of protocols if all methods are optional?

I understand what purpose protocols serve (to have a type conform to a set list of methods or/and properties), but I don't understand what the purpose is of a protocol with all optional methods. One example would be UITextFieldDelegate.
If all methods are optional in a protocol, why would you conform to the protocol instead of just writing the methods from scratch in your class? I don't see what the benefit or purpose of conforming to the protocol is in this case.
Are the optional methods there just as suggestions of functionality that could be implemented?
Historically, for delegates and data sources in Cocoa, informal protocols were used. Informal protocol was implemented trough a category for NSObject class:
#interface NSObject (NSTableViewDelegate)
- (int)numberOfRowsInTableView:(NSTableView *)tableView;
// ...
#end
Later, optional methods in protocols were introduced. This change leads to better documenting of class responsibilities. If you see in code, that class conforms to NSTableViewDelegate, you suspect that somewhere exists a table view, that managed by instance of this class.
Also, this change leads to stronger checks in compile time. If programmer accidentally assign wrong object to delegate or dataSource properties, compiler will warn.
But your assumption is also correct. Optional methods are also suggestions for possible functionality.
By default, all methods in a protocol are required. Each method has to be marks as optional if the nor required for everything to function correctly.
If all methods are optional in a protocol, why would you conform to the protocol instead of just writing the functions from scratch in your class?
Conforming to a protocol allow your class to tell another object the methods it has without the other object needing to know about your class. This is really useful when using Delegation as it allows the delegate to decide what information they wish to receive/provide to another class.
For example,the UIScrollViewDelegate protocol only defines optional methods. Lets say we have a class Foo that we want to know when things change with a UIScrollView.
If we decided to throw that protocol away and implement the functions from scratch, how would we tell UIScrollView which methods we implement and which methods to call when certain event occur? There is no good way it could find out. When UIScrollView was built, it didn't know about Foo so it can't know what methods it implements. Also, Foo has no way of knowing what methods can be called on it by the UIScrollView.
However, when UIScrollView was built, it did know about UIScrollViewDelegate. So if Foo conforms the the UIScrollViewDelegate protocol, there is now a common definition that both Foo and UIScrollView can follow. So Foo can implement any methods it cares about, like scrollViewDidScroll: and the UIScrollView just needs to check if the delegate implemented the methods in UIScrollViewDelegate.
The protocol establishes a contract for the interface between one object and another. The fact that the methods are optional simply says that you don't have to implement that particular method, but you can if your app calls for it.
Generally, if you're conforming to a protocol for which all of the methods are optional, though, you're doing that for a reason, namely that you plan on implementing one or more of those methods. Just because all of the protocol's methods are optional doesn't mean you will not implement any of them, but rather simply that you can elect which are relevant in your particular situation.
For example, consider the UITextFieldDelegate protocol. You'd generally conform to that because you want to specify, for example, whether certain characters should be allowed to be inserted into the text field or what to do when the return key is pressed. Sometimes you only want to implement the former. Sometimes you only want to implement the latter. Sometimes you do both. But just because you choose to implement one or the other doesn't mean you necessarily want to do other one (but you can if you want). Frankly, though, if you really didn't want to implement any of the methods, you probably wouldn't even bother to specify the delegate of the text field, nor bother to specify that you're conforming to the protocol.
Bottom line, the protocol that consists solely of optional methods basically says "if you need it, this is the documented interface for the methods you may elect to implement". The protocol still is very useful to establish the possible interfaces, but doesn't force you to implement those methods you do not need.

delegates in ruby explained from a Cocoa developer background

I really hope someone can answer this one. I think I am definitely not the only one confused about this and I wasn't able to find anything that clearly explains this concept.
My understanding of the delegation pattern comes from studying the Cocoa framework. To me, the Cocoa implementation is very clear. But I am having a very hard time understanding it in Ruby (standard library's Delegator, SimpleDelegator vs. ActiveSupport's Delegate). It makes little sense to me. Mostly because one is type safe the other is duck type. You can see my point already, but allow me to expand... Here is my summary of how to use the delegate pattern in Cocoa:
Our "ingredients" are: 2 classes, A and B and a protocol, which is Cocoa for a pre-defined set of methods to use for delegation.
The implementation of the pattern is basically as follows:
A defines the set of methods to delegate to B.
B's delegate is set to be A
=> B can now call delegated methods like so: #delegate.send(a_delegated_method)
What I am not tying together is the fact that Ruby uses duck typing, so you can send any method call to any object, right? So using the pattern I just explained, as long as the 2 objects are in the same domain you can say while in A #b.send(:a_delegated_method) and vice versa while in B #a.send(:another_delegated_method).
Could it be that the point with delegates in Ruby is where the delegated method is defined? Meaning that we send from within class A to property #b (#b(:delegated_method)) a :delegated_method defined within A itself?
Hope this isn't too confusing. I myself am confused about why delegates even exist in a duck typing language and what the differences are between Delegator, SimpleDelegator and ActiveSupport's Delegate.
It isn't clear to me that you have understood how delegation works in Cocoa. It is true that the common variety of the delegation pattern in Cocoa involves a protocol, but that's just a way of quieting the compiler.
So let's talk first about quieting the compiler. You can't send the woohoo message to an object in Objective-C unless one of two things is true:
The compiler has reason to believe that this object might respond to the woohoo message.
The compiler is made to suspend judgment.
Nowadays, the first approach is usually used - that's what a protocol is for. But this was not always the case. It used to be that delegation depended mostly on informal protocols. And there still are informal protocols in Cocoa. The idea is that either the method is injected into NSObject by a category, or else you are careful to type the object as id so that it can be sent any message at all.
Now let's talk about dynamism. The reason informal protocols are no longer used is that a feature was introduced allowing protocols to declare optional members. But dynamism is still needed! We may satisfy the compiler, one way or another, but at runtime we have to make sure that it is safe to send a certain message to a certain object. Your app delegate may adopt UIApplicationDelegate, but Cocoa is not going to send it the applicationDidBecomeActive: message unless your app delegate class implements applicationDidBecomeActive: - if it did, you'd crash, and that wouldn't be very nice.
Moreover, if you can just get past the compiler, you can perform delegation in Objective-C even more dynamically than that, as explained here:
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtForwarding.html
The idea is that we go right ahead at runtime and send the object the message anyway! If a message arrives that Object A can't handle, it can see if Object B handles it. If it does, it passes the message along to Object B. So we might not crash after all!! I use that approach in one of my apps:
- (id)forwardingTargetForSelector:(SEL)aSelector {
if ([self.originalDataSource respondsToSelector: aSelector])
return self.originalDataSource;
return [super forwardingTargetForSelector:aSelector];
}
In that code, I'm saying that if a message arrives and I can't handle it, I should try to get it sent on to another object, called self.originalDataSource.
If you think about it, that is almost identical to Ruby delegation. I have a helper object, and messages that I can't handle are passed on to it.
Another common use of this pattern is when wrapping a Cocoa collection. You can't subclass, say, NSArray, because it's a class cluster, so the proper approach is to wrap it. You then just forward everything to the NSArray, and presto, you are duck-typed as an NSArray! You look like an NSArray as far as your methods are concerned. Then you introduce some difference in behavior, and now you are duck-typed as a customized NSArray.

Why use delegate and protocol instead of just passing an instance in Swift?

I was trying to pass around variables between views in Swift, and ran into the rather abstract concept of protocols and delegates.
Then I tried storing a reference to the first view in a second view and call functions on that directly. This seems to work:
SCREEN 1
class Screen1: UIViewController {
var myName = "Screen1"
override func viewDidLoad() {
super.viewDidLoad()
}
//
// checking if the segue to screen 2 is called and then passing a reference
//
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "screen2Segue"{
let vc = segue.destinationViewController as Screen2
vc.storedReference = self
}
}
func getName() -> String {
return myName
}
}
SCREEN 2
class Screen2: UIViewController {
var storedReference:Screen1!
override func viewDidLoad() {
super.viewDidLoad()
}
func testReference() {
// calling a function on the stored reference to screen 1
var str = storedReference.getName()
println("Leaving screen 2, going to " + str)
}
}
My question: what's wrong with this code? Why use delegates and protocols if you can just pass around a reference directly?
Perhaps related: when does a view get un-initialized and replaced by an entirely new view instance? Am I calling 'getName()' on an old instance?
Protocols are useful for separating implementation from interface, which helps increase code reusability, understandability, and testability.
For example, perhaps you wish to store items in a List of some sort. Some possible implementations of a List include array-based implementations and node-based (linked-list) implementations. If you were to declare a protocol called List and have classes ArrayList and LinkedList that implemented that protocol, anything that required the use of a list (variable passed as a parameter to a method, a property, etc) could use List as the variable type, and be able to function without caring about whether a the list was an ArrayList or a LinkedList. You could change which type was used, or how they were implemented, and it would not matter to whatever was using them, because only the exposed interface declared in the protocol would be visible.
Protocols can also be useful for emulating something like multiple inheritance, as a class can inherit from a superclass, as well as implement one or more interfaces. (eg. A bat is both a mammal and winged, so it could be represented as a Bat class inheriting from a Mammal class that implements the Winged protocol).
The delegate pattern uses protocols to delegate some responsibilities to another object, which is especially good for code separation and reusability. For example, the UITableViewDelegate protocol in iOS allows a UITableView to react to things like cell selection by delegating another object to handle the event. This has probably been used by millions of objects in thousands of applications, without the developers at Apple who implemented UITableView and UITableViewDelegate having ever known anything about the objects that were implementing the protocol.
By directly passing a reference between your view controllers, you are forcing the second to be completely dependent upon the first. If you ever wished to change the flow of your application so that the second view controller could be accessed from somewhere else, you would be forced to rewrite that view controller to use the new origin. If you use a protocol instead, no changes to the second view controller would have to be made.
It is a basic design principle to not expose any more of a design than you have to. By passing the reference around you are exposing the whole object. Which means that others can call any of its functions and access any of its properties. And change them. This isn't good. Besides letting others use the object in ways it might not have intended, you will also run into issues if you try to change the object in the future and find out that it breaks somebody else who was using something you didn't intend. So, always a good idea to not expose anything that you don't have to. This is the purpose of delegates and protocols. It gives the object complete control over what is exposed. Much safer. Better design.
I think you didn't fully get the understanding what protocols are.
I always say protocols are like contracts.
The delegate object that implements a certain protocols promises that it can do things the delegator can't do.
In real world I have a problem with my house's tubes.
I (the delegator) call a plumber (the delegate) to fix it. The plumber promises (by contract) to be able to duo it. The promise is the protocol. I don't care how he do it, as long as he does it.
But these contracts are not only useful for delegation.
I am just writing a food ordering app. As it has a menu it need item to display in it.
I could go with basic inheritance and write a class MenuItem, that all sub classes must inherit from.
Or I write an protocol to express: «No matter what object you are, as long as you fulfill this contract we have a deal». this allows me to create many different classes or annotate existing classes in categories, although I don't have the tool of multiple inheritance.
Actually I do both: I write a protocol MenuItem and a class MenuItem that conforms to the protocol. Now I can use simple inheritance or use classes that do not inherit from the class MenuItem.
Code in Objective-C (sorry: I am still transitioning to Swift)
#protocol MenuItem <NSObject>
-(NSString *)name;
-(double) price;
-(UIColor *)itemColor;
#end
#interface MenuItem : NSObject <MenuItem>
#property (nonatomic, copy) NSString *name;
#property (nonatomic, assign) double price;
#property (nonatomic, strong) UIColor *itemColor;
#end
#import "MenuItem.h"
#implementation MenuItem
-(id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if (self) {
self.name = [decoder decodeObjectForKey:#"name"];
self.price = [decoder decodeDoubleForKey:#"price"];
self.itemColor = [decoder decodeObjectForKey:#"itemColor"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeDouble:self.price forKey:#"price"];
[encoder encodeObject:self.name forKey:#"name"];
[encoder encodeObject:self.itemColor forKey:#"itemColor"];
}
#end
Apple uses the same Architecture for NSObject: there is a protocol and a class NSObject. This allows classes, that aren't intact inheriting from the class NSObject to act ash an NSObject. One famous example:NSProxy.
in your case Screen1 promises to be able to understand messages that are send by the detail view controller Screen2. These allows decoupling: any object that does understand Screen1's protocol can be used. Also it helps to maintain a sane object tree, as we don't have to have circular imports. But in general you have to keep in mind that the delegator (Screen2) must keep a weak reference to it's delegate, otherwise we have a retain circle.
Of course an important example it UITableView:
The table view object knows everything about rendering it's cells, handling scrolling and so one. But the engineer who wrote it couldn't now how you want your table view look like. That's why he introduced a delegate to give you the chance to create the right cell. As he couldn't also know what your data looks like, he also introduced the datasource - that works exactly like a delegate: you will be asked to provide all information about your data, that are needed.
This is mostly a matter of opinion so this question should probably be closed, but I think the developer community as a whole is in an agreement on this so I am going to answer it anyway.
An important concept in Software Architecture (the design of the structure of code) is called Separation of Concerns. The basic principle is that you should break down what your code has to do into small components that only have one distinct purpose. Each of these components should be able to stand mostly on their own without much concern with other components other than the ones it needs to directly be interacting with.
This helps greatly with code reuse. If you design a small component that is independent of most / if not all other components, you can easily plug that into other parts of your code or other applications. Take UITableView for example. By using the delegate pattern, every developer can easily create a table view and populate it with whatever data they want. Since that data source is a separate object (with the separate concern of coming up with the data) you can attach that same data source to multiple table views. Think of a contact list on iOS. You will want to access that same data in many ways. Instead of always rewriting a table view that loads the specific data and displays it in a specific way, you can reuse the data source with a different table view as many times as you want.
This also helps with the understandability of your code. It is tough for developers to keep too many thing in their head about the state of your app. If each of your code components are broken down into small, well defined responsibilities, a developer can understand each component separately. They can also look at a component, and make accurate assumptions about what it does without having to look at the specific implementation. This isn't such a big deal with small apps, but as code bases grow, this becomes very important.
By passing in a reference to your first view controller, you are making your second view controller completely dependent on the first. You cannot reuse the second view controller in another instance and its job becomes less clear.
There are lots of other benefits to separation of concerns but I believe those are two compelling and important ones.
I think the problem with the latter arises with multiple reuse of a single class.
Take for example a custom UITableViewCell called CustomTableViewCell. Let's say you have Class A and Class B which both have tableViews and both would want to use CustomTableViewCell as their cell. You now have two options. Would you rather:
A. Use a delegate/protocol for CustomTableViewCell called CustomTableViewCellDelegate. Declare a single object inside the class CustomTableViewCell named "delegate" which implements the mentioned protocol and call on that regardless of what class it calls on
or
B. Declare an object for each class (Class A, Class B) inside CustomTableViewCell so you can hold a reference to each of them.
If you need to use CustomTableViewCell for a number of classes, then I think you know which option to take. Declaring multiple objects for different classes inside CustomTableViewCell would be a pain to see from a software architecture standpoint.

How is Key-Value Observing implemented internally?

I got answer about Foundation magic for this question: What's the most *simple* way to implement a plain data object which conforms key-value-observing?
What's the magic? How it work internally? Because it's dangerous using framework which I can't understand its internal behavior, I want to know its behavior. Currently, I cannot understand how it work without any method definitions.
Apple's documentation describes how KVO is implemented internally.
The gist of it is that when you register an observer on an object, the framework dynamically creates a subclass of the object's original class, and adjusts the object to appear as an instance of this new dynamic class. You can see this if you inspect an object in the debugger after it has had an observer registered.
This new class intercepts messages to the object and inspects them for those matching certain patterns (such as the getters, setters, and collection access).
In a nutshell: Objective-C 2.0's #property declaration creates accessor methods for the named property, so there are method definitions. #property is just a shorthand way to define them which avoids a lot of repetitious boilerplate code.
When you observe a property, a private subclass is created which implements accessors that call the appropriate notification methods before and after changing the property value. A technique known as "isa swizzling" is then used to change the class of the observed object.

Does Objective-C support Mixin like Ruby?

In Ruby, there's Modules and you can extend a class by "mixing-in" the module.
module MyModule
def printone
print "one"
end
end
class MyClass
include MyModule
end
theOne = MyClass.new
theOne.printone
>> one
In Objective-C, I find that I have a set of common methods that I want a number of Class to "inherit". What other ways can I achieve this without creating a common class and deriving all from that common class?
Shameless plug: ObjectiveMixin
It takes advantage of Objective-C runtime's capability of adding methods to a class in runtime (as opposed to categories, which are compile-time only). Check it out, it works pretty good and in a similar fashion to Ruby's mixins.
Edit: changes added because some people feel I am responsible for the limitations of Objective-C.
Short answer: you can't. Objective-C doesn't have the equivalent of Ruby mixins.
Slightly less short answer: Objective-C does have something with arguably the same flavour: protocols. Protocols (Interfaces in some other languages), are a way to define a set of methods an class that adopts that protocols is committing to implementing. A protocol doesn't provide an implementation though. That limitation prevents using protocols as an exact equivalent to Ruby mixins.
Even less short answer: However, the Objective-C runtime has an exposed API that lets you play with the dynamic features of the language. Then you step outside the language, but you can have protocols with default implementations (also called concrete protocols). Vladimir's answer shows one way to do that. At that point it seems to me you get Ruby mixins alright.
However, I am not sure I would recommend doing that. In most cases, other patterns fit the bill without playing games with the runtime. For example, you can have a sub-object that implement the mixed-in method (has-a instead of is-a). Playing with the runtime is OK, but has 2 drawbacks:
You make your code less readable as it requires readers to know a lot more than the language. Sure you can (and should) comment it, but remember that any necessary comment can be seen as an implementation defect.
You depend on that implementation of the language. Sure, Apple platforms are by far the most common ones for Objective-C but don't forget Cocotron or GnuStep (or Etoilé) which have different runtimes, which may or may not be compatible with Apple's on that respect.
As a side note, I state below that categories cannot add state (instance variables) to a class. By using the runtime API, you can lift that limitation too. This is beyond the scope of this answer however.
Long answer:
Two Objective-C features look like possible candidates: categories and protocols. Categories are not really the right choice here, if I understand the question properly. The right feature is a protocol.
Let me give an example. Suppose you want a bunch of your classes to have a specific ability called "sing". Then you define a protocol:
#protocol Singer
- (void) sing;
#end
Now you can declare that any of your own classes adopts the protocol the following way:
#interface Rectangle : Shape <Singer> {
<snip>
#end
#interface Car : Vehicle <Singer> {
<snip>
#end
By declaring that they adopt the protocol they commit themselves to implementing the sing method. For example:
#implementation Rectangle
- (void) sing {
[self flashInBrightColors];
}
#end
#implementation Car
- (void) sing {
[self honk];
}
#end
Then you use those classes for example like this:
void choral(NSArray *choir) // the choir holds any kind of singer
{
id<Singer> aSinger;
for (aSinger in choir) {
[aSinger sing];
}
}
Notice that the singers in the array don't need to have a common superclass. Notice also that a class can have only one superclass, but many adopted protocols. Notice finally that type checking is done by the compiler.
In effect, the protocol mechanism is multiple inheritance used for the mixin pattern. That multiple inheritance is severely limited because a protocol cannot add new instance variables to a class. A protocol only describes a public interface adopters must implement. Unlike Ruby modules it does not contain an implementation.
That's the most of it. Let's mention categories however.
A category is declared not in angle brackets, but between parenthesis. The difference is that a category can be defined for an existing class to expand it without subclassing it. You can even do so for a system class. As you can imagine, it's possible to use categories to implement something similar to mixin. And they were used that way for a long time usually as category to NSObject (the typical root of the inheritance hierarchy), to such an extent that they were called "informal" protocols.
It's informal because 1- no type checking is done by the compiler, and 2- implementing the protocol methods is optional.
There is no need today to use categories as protocols, especially because the formal protocols can now declare that some of their methods are optional with the keyword #optional or required (the default) with #required.
Categories are still useful to add some domain specific behavior to an existing class. NSString is a common target for that.
It's also interesting to point out that most (if not all) of NSObject facilities are in fact declared in a NSObject protocol. This means that it's not really compelling to use NSObject as a common superclass for all classes, though this is still commonly done for historical reasons, and well... because there is no drawback for doing so. But some system classes, such as NSProxy, are not NSObject.
You can literally mixin the code using #include. This is not advisable and is against all the religions in objective-c, however works perfectly.
Please, don't do it in the production code.
for example in the file:
MixinModule.header (should not be compiled or copied to the target)
-(void)hello;
MixinModule.body (should not be compiled or copied to the target)
-(void)hello{
NSLog(#"Hello");
}
in mixin class:
#interface MixinTest : NSObject
#include "MixinModule.header"
#end
#implementation MixinTest
#include "MixinModule.body"
#end
usage case:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]){
#autoreleasepool {
[[[MixinTest new] autorelease] hello];
}
return 0;
}
Please, don't do it in the production code.
This is my take on implementing Mixins in Objective-C, without using the Objective-C runtime directly. Maybe it's helpful to someone: https://stackoverflow.com/a/19661059/171933

Resources