Why should I conform Custom Protocol to NSObject? - ios

Any object which assign to Custom protocol reference, is always be Confirm by NSObject Protocol directly or By superclasses. So Why should I do this?

I really don't know, whether I got you right.
If you meant that a custom protocol always confirms to the NSObject protocol, there is a pretty simply reason for it. It is a little bit weird:
If you type a reference to id the compiler accepts every message to that he has seen while compiling the translation unit ("class", "module", the file you compile).
If you type an object reference to id<protocol>, the compiler only accepts messages that are declared inside the protocol. But this is never enough!
#protocol MyProtocol
#optional
- (void)doItOrNot;
#end
The only message you can send is -doItOrNot. So the compilation of such code will fail:
id<MyProtocol> ref = …;
if ([ref respondsToSelector:#selector(doItOrNot)]) // <- Error -respondsToSelector is not declared in the protocol.
…
By adding the NSObject protocol to your protocol you import some fundamental declarations. (Including MM for MRC.)

It sounds like you might be trying to ask about using the NSObject protocol, since every class has NSObject as an ancestor.
The answer, then, is that it's not true that every object is derived from NSObject. Most are, but NSProxy is an example of one that's not. The methods in the NSObject protocol are what any instance of the NSObject class is expected to implement, so by implementing the NSObject protocol, NSProxy is able to provide the same behaviors that any class derived from NSObject (class) has.
For example, you can use methods like -isEqual and -hash with instances of NSProxy.
If you're creating a subclass of the NSObject class, there's no need to declare that your class implements the NSObject protocol because the NSObject class already does that for you.
Also, just as you can declare that a class adopts a protocol with:
#interface MyClass <SomeProtocol>
you can also declare that a protocol adopts another protocol:
#interface MyProtocol <SomeProtocol>
Since, as explained above, not every class is a subclass of NSObject (the class), having MyProtocol adopt NSObject (the protocol) guarantees that you can call NSObject methods. If you want to specify that a method takes any kind of object that adopts YourProtocol, you can do that by specifying the type as id<YourProtocol>. However, if YourProtocol isn't declared to adopt the NSObject protocol, you can't be certain that it's safe to call NSObject methods like -isEqual, and you can't even check that it's safe using -respondsToSelector: or -isKindOfClass: because those methods themselves are part of the NSObject protocol.

Cocoa defines an NSObject protocol that mirrors the NSObject class and instance methods. By declaring that your custom protocol implements the NSObject protocol, you give the compiler a hint that all of the NSObject methods will be implemented by an instance that implements your custom protocol.
If you don't include the NSObject protocol, you'll get warnings when you try to call any of the NSObject methods for instance respondsToSelector: on the object.

You don't have to. But the problem is that a lot of the core functionality of NSObject — indeed, all the core functionality necessary for NSObject to function as a base class — is declared in the NSObject protocol. (This strange architecture is so that both NSObject and NSProxy can be base classes: they both adopt the NSObject protocol.)
Now, if you declare an object's type as id<MyDelegate>, the only messages you can send that object are MyDelegate messages. That's fine, usually; but what if you want to send it, say, the respondsToSelector: message? That method is declared in the NSObject protocol, not in the MyDelegate protocol. So the compiler will stop you.
There are two solutions. Either declare the object's type as NSObject<MyDelegate>, or make MyDelegate adopt the NSObject protocol. Either way, the compiler is now satisfied, and you can send this object the respondsToSelector: message.

Related

Use __attribute__((objc_requires_super)) with protocol

I have something like this:
#protocol MyProtocol <NSObject>
- (void)oneMethod;
#end
.
#interface BaseClassWithProtocol : NSObject <MyProtocol>
#end
.
#interface ChildClassWithProtocol : BaseClassWithProtocol
#end
BaseClassWithProtocol has implemented oneMethod, and I want to show warning if ChildClassWithProtocol doesn't call super in its oneMethod implementation.
But I don't know where should I write __attribute__((objc_requires_super)).
Writing it in protocol is not supported while redefining oneMethod in .h looks stupid.
So is there any standard way which can deal with the problem?
The requirement to call super is imposed by BaseClassWithProtocol. It's not part of the protocol. Surely, some class could implement MyProtocol however it wants without that requirement being imposed. That's the nature of protocols. They impose interface, not implementation.
So, redeclaring the method in BaseClassWithProtocol with the attribute seems perfectly sensible to me. Not sure why it "looks stupid".
Protocols aren't meant to give warnings for your diverse implementations. They only warn you whether you agree to include the required methods in your implementation or not. But how you implement the methods, that's up-to your Base class that adopts the protocol. That is, you should have your necessary functionalities in your .h or .m files.
Consider this way:
You have a method in your protocol where you want to have a warning for the super calls. Now you adopt the protocol in a class which is the sub-class of NSObject. But the NSObject class doesn't conform to the protocol you are defining. Would you now supposed to get the warning for your class? According to your requirements, you should get that warning. But this isn't the case. You would practically never get that warning by this procedure.

How to override the NSObject methods without inheriting from NSObject in swift

I actually want to know how to access the encodeWithCoder, init etc methods from the NSObject or any other class without inheriting from NSObject class.
Because I read that if we inherit from the NSObject class then it has performance issues in Swift or similar performance to the Objective - C.
So please let me know how to do it.
You want to override a super class method from a class that doesn't inherit from that super class, this doesn't make sense. If you need to use encodeWithCoder method, you'll have to extend NSObject class or any other class that conforms to NSCoding protocol. Otherwise you can create your custom class that conforms to NSCoding protocol and implement the same functionality in encodeWithCoder method.
From Apple documentation
Any class that does not inherit from another class is known as a base class.
NOTE
Swift classes do not inherit from a universal base class. Classes you
define without specifying a superclass automatically become base
classes for you to build upon.

what's the use of greater/less then sign in Objective-C <>

Hi what's the use of < > in ios? I can't find some documentation of that.
Here's an example of it's use
id < TYPE >
I hope someone can help me with my problem. Thanks in advance guys.
It means it's a generic object pointer that conforms to the specified protocol.
Therefore:
#protocol SomeProtocol <NSObject>
- (void)someMethod:(int)a;
#end
#interface SomeClass : NSObject <SomeProtocol>
#end
Would allow:
SomeClass *obj = [SomeClass new];
// call method via the protocol interface
id<SomeProtocol> iface = obj;
[iface someMethod:1];
It indicates that a class adopts a protocol (specified within the '<>')
See apple documentation here: https://developer.apple.com/library/ios/documentation/cocoa/conceptual/programmingwithobjectivec/workingwithprotocols/workingwithprotocols.html
By the way, it is a language feature rather than an OS one. You should label your question as objective-c rather than iOS
It's part of a class definition (#interface) or a type defining a variable. Its a way of telling the compiler thatthe class/type implements a protocol. The name of the protocols the class implements are inside the triangular brackets separated by commas.
In your case:
id <protocolName> object;
Means that you are declaring a variable called object of type id that implements the protocol protocolName.
A protocol is a collection of methods. So it allows you to send messages defined by protocolName to object without the compiler issuing warnings.
Apple docs here.

What does the <> means in an iOS class header?

The AppDelegate.h file contains the following at the top of the line:
#interface AppDelegate : UIResponder <UIApplicationDelegate>
The current class is AppDelegate which is a subclass of UIResponder. What is the relationship of UIApplicationDelegate with the current class?
It declares that the class conforms to the UIApplicationDelegate protocol.
An Objective-C protocol is similar to a Java interface: it can declare method signatures but it can't provide method implementations.
The compiler will warn you if your #implementation is missing any of the #required methods of the protocol. Xcode will autocomplete any of the methods (#required or #optional) of the protocol.
You can declare conformance to multiple protocols by separating them with commas. Example:
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
Read Cocoa Core Competencies: Protocol and Programming with Objective-C: Working with Protocols.
This mean that your class implement UIApplicationDelegate protocol. Here you have something about protocols : https://developer.apple.com/library/ios/documentation/general/conceptual/devpedia-cocoacore/Protocol.html
You must implement a required methods from implemented protocol into your class, if you want to have class fully accordance with the protocol.

What exactly are protocols and delegates and how are they used in IOS?

I'm really confused about the concept of delegates and protocols. Are they equivalent of interfaces and adapter classes in Java? How do they work?
None of the resources I've read were helpful so far.
"Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it." I have no idea what this means.
Can someone please explain what they are and give a simple example? Thanks in advance!
EDIT:
As far as I now understand,
1) delegates implement protocols (another name for interfaces)
2) object registers a delegate (that implements a protocol)
3) object can call protocol methods on the delegate
Therefore, a delegate is connecting the object with the protocol.
Please correct me if I'm wrong.
I still don't understand why the object itself can't implement a protocol? It could've been so much easier!
Protocols are a way to specify a set of methods you want a class to implement if it wants to work with one of your classes. Delegates and Data Sources like UITableViewDelegate and UITableViewDataSource are protocols indeed.
You specify a protocol this way:
#protocol MyProtocol <NSObject>
- (void)aRequiredMethod;
#required
- (void)anotherRequiredMethod;
#optional
- (void)anOptionalMethod;
#end
Methods declared after the #required or before any other specifier are required and the classes that want to use your protocol need to implement all of them. You can also declare some optional methods by declaring them after the #optional specifier.
You then can specify that a class "conforms" to a protocol (implements the required methods) in the interface of the class:
#interface MyClass <MyProtocol>
#end
You usually keep a reference to an object conforming to a protocol using a property. For example, to keep track of a delegate:
#property (nonatomic, weak) id<MyProtocol> delegate;
At this point, in your code, you just have to call the method you want to call on the object that you're keeping reference of and that implements your protocol as you would with any other method:
[self.delegate aRequiredMethod];
To check whether an object conforms to a protocol you can call
[self.delegate conformsToProtocol:#protocol(MyProtocol)]
To check whether an object implements a method you can call
[self.delegate respondsToSelector:#selector(anOptionalMethod)]
For more information, check the Apple's guide Working With Protocols.
A protocol which declared with the (#protocol syntax in Objective-C) is used the declare a set of methods that a class that "adopts" (declares that it will use this protocol) will implement. This means that you can specify in your code that, "you don't care which class is used so long as it implements a particular protocol". This can be done in Objective-C as follows:
id<MyProtocol> instanceOfClassThatImplementsMyProtocol;
If you state this in your code, then any class that "conforms" to the protocol MyProtocol can be used in the variable instanceOfClassThatImplementsMyProtocol. This means that the code that uses this variable knows that it can use whichever methods are defined in MyProtocol with this particular variable, regardless of what class it is. This is a great way of avoiding the inheritance design pattern, and avoids tight coupling.
Delegates are a use of the language feature of protocols. The delegation design pattern is a way of designing your code to use protocols where necessary. In the Cocoa frameworks, the delegate design pattern is used to specify an instance of a class which conforms to a particular protocol. This particular protocol specifies methods that the delegate class should implement to perform specific actions at given events. The class that uses the delegate knows that its delegate coforms to the protocol, so it knows that it can call the implemented methods at given times. This design pattern is a great way of decoupling the classes, because it makes it really easy to exchange one delegate instance for another - all the programmer has to do is ensure that the replacement instance or class conforms to the necessary protocol (i.e. it implements the methods specified in the protocol)!
Protocols and delegates are not restricted only to Objective-C and Mac/iOS development, but the Objective-C language and the Apple frameworks make heavy use of this awesome language feature and design pattern.
Edit:
Please find this Example. In the UIKit framework of Cocoa Touch, there is a UITextFieldDelegate protocol. This protocol defines a series of methods that classes which are delegates of a UITextField instance should implement. In other words, if you want to assign a delegate to a UITextField (using the delegate property), you'd better make sure that this class conforms to UITextFieldDelegate. In fact, because the delegate property of UITextField is defined as:
#property(nonatomic, assign) id<UITextFieldDelegate> delegate
Then, the compiler will give warnings if you assign a class to it that doesn't implement the protocol. This is really useful. You have to state that a class implements a protocol, and in saying that it does, you're letting other classes know that they can interact in a particular way with your class. So, if you assign an instance of MyTextFieldDelegateClass to the delegate property of UITextField, the UITextField knows that it can call some particular methods (related to text entry, selection etc.) of your MyTextFieldDelegateClass. It knows this because MyTextFieldDelegateClass has said that it will implement the UITextFieldDelegate protocol.
Ultimately, this all leads to much greater flexibility and adaptability in your project's code, which I'm sure you'll soon realise after using this technology! :)
In it's simplest form a delegate is an object which receives messages from another object. And you do it all the time.
So say you had car object with an engine.
#interface car : NSObject
#property (nonatomic) id engine;
#end
So could forward a start message to the engine.
[_engine start];
The engine is acting as a delegate, you're just passing it a message.
Protocols make it more formal, and Xcode will check that you are conforming to the required or optional methods.
#property (nonatomic) id <engineDelegate> engine;
says that the engine object MUST contain the function start because in the the protocol definition it asked for it.
#protocol engineDelegate
- (void) start;
#optional
- (double) fuelLevel;
#end
Why are delegates and protocols so cool? Well because the engine could be any number of different engines which you could use at runtime, it could be a jet engine, a combustion engine, a phasing modulating engine it doesn't matter, as long as it conforms to the protocol. And you tell Xcode that it does conform by adding the delegate to the class interface.
#interface timeWarpDrive : NSObject <engineDelegate>

Resources