Use __attribute__((objc_requires_super)) with protocol - ios

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.

Related

Why should I conform Custom Protocol to NSObject?

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.

Same Protocol defined in multiple class

Is it possible to define a same protocol with different methods in different classes?
Ex:
In classA.h
#protocol ME_DELEGATE <NSObject>
#required
-(void)doThis;
#end
In classB.h
#protocol ME_DELEGATE <NSObject>
#required
-(void)doThat;
#end
Am I doing it right?
#Siddharthan Asokan
You can have the same protocol in two different classes and the system will generate a warning "Duplicate protocol definition of 'protocolName' is ignored" (with the default settings)
You can make it work if you declare the protocol methods as #required or #optional.
Also, If you want to have 2 different objects being the delegates for the same protocol, then as already suggested, you need to have the protocol methods defined as #optional... I have tested and it works.... The trickier part is to get the reference to the objects to set the second delegate properly
I added an exercise to show how it works both ways.... Same protocol in two classes and then 2 different objects being the delegates of the same protocol. It also shows how to have 2 delegates to the same class, in the same protocol.
https://github.com/eharo2/ProtocolTest
Given that the protocols are based in the message passing paradigm, with the proper object reference and method implementation, you can do pretty much what you want.
I hope it helps... e

How to make all subclasses necessarily conform to protocol?

I have a base class SLBaseViewController which is a subclass of UIViewController and want all its subclasses to conform to protocol:
#protocol SLLocalizable <NSObject>
- (void)localize;
#end
The problem is that I don't need SLBaseViewController to conform to protocol itself, but I need compiler to warn me if a subclass doesn't conform.
What I have tried:
Define base class like this:
#interface SLBaseViewController : UIViewController <SLLocalizable>
In this case compiler tells me that SLBaseViewController does not implement localize method.
Make localize optional.
Compiler keeps silence. But that's not what I need.
Make each of subclasses conform to protocol itself. That seems to be a right way, but I have more than 50 subclasses and it's a long way.
Is there a simple way to reach my goal?
You can't specify that the subclasses implement any protocol other than to specify it in the subclass itself.
Search for the subclasses to edit them (rather than trying to remember each). A reflex search would be able to find subclasses which don't give the protocol name.
As a safety check, make the superclass throw an exception if it's called so you know when you missed something. Obviously this only works during testing.
If this makes you paranoid, you could try writing a unit test which gets all the subclasses and calls localize on them.
In what case would you need all subclasses to implement something, but don't need the common superclass to implement it?
If it is that SLBaseViewController is an abstract class that is not meant to be instantiated directly, you can simply have it implement -localize, and in the body throw an exception. Or, you can simply ignore the warning (it is just a warning after all).

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>

xcode basic explanation needed

I am actually a newby at xcode. I can make out a few things be myself but have questions about what some things do and why they are put there. I have tried to read many e-books, watched tutorials, but they never go into the basics, alway just say "Add this, Click here etc"
Could someone give me some answers to a few questions please.
Ok, I know an ios app is mostly made out of Views, views are controlled by controllers. Each controller has a header (.h) file and a module?class? file (.m). The .h file contains the declarations of variables and functions used in the .m file.
The whole app is controlled by a master "controller" called the "delegate".
Definitions in .h file may be for example an action IBAction or IBLabel or something.
What raises questions for me is for example these lines:
#class FlipsideViewController;
#protocol FlipsideViewControllerDelegate
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller;
#end
#interface FlipsideViewController : UIViewController
#property (nonatomic, assign) id <FlipsideViewControllerDelegate> delegate;
- (IBAction)done:(id)sender;
and why are sometimes in another view controller the delegate class loaded
#class MainViewController;
what does the following do, meaning what is the #interface declaration?
#interface flipAppDelegate : NSObject <UIApplicationDelegate>
what is
nonatomic, retain
sorry for asking really stupid questions, but every tutorial just skips these things.
I can follow a youtube video or a manual, but it doesn't teach me a lot...
Let me try to answer your questions, one at a time.
what is the #interface declaration?
The interface declares a class. By declaring a class, I mean it specifies the instance variables and private/public methods that it contains. Again, the header file only contains the declaration of the methods, and the implementation/body of the methods lies in the module class. So, here-
#interface FlipsideViewController : UIViewController
The class FlipsideViewController derives from/subclasses/extends UIViewController. i.e Is a type of UIViewController but adds its own features.
Similarly
#interface flipAppDelegate : NSObject <UIApplicationDelegate>
Subclasses NSObject and implements the UIApplicationDelegate protocol. A protocol is essentially a set of methods that a class promises to implement (although there can be optional methods).
why are sometimes in another view controller the delegate class loaded
The delegate pattern allows a class to delegate its work to another class that implements the delegate protocol. So, here, FlipsideViewController keeps an instance of the delegate object, so that its flipsideViewControllerDidFinish: can be called.
what is nonatomic, retain
It means that when you set a value to your instance variable, the value's refcount will be incremented and set to your variable. Also, it will not happen as an atomic operation. You need atomic only in a multi-threaded environment.
#synthesize is simply a shortcut to generate getters and setters for your variables.
You really need to read the Objective-C Programming Language from Apple. It's pretty brief, and runs down the basics of the architecture, concepts, and syntax.
To address, briefly, some specifics:
The #class directive is used to declare the name of a class without importing it's header file. It is often used in a .h file declaring a protocol, because a protocol has no implementation, it doesn't need to import the interfaces of other classes (their .h files).
A protocol is a way of declaring what methods and properties a class should have in order to "implement" the protocol.
#interface is used in an interface file (.h) to declare a class, meaning to describe the methods and properties it will have, the protocols it will implement, and the superclasses from which it will inherit. In your example, the class will be called flipAppDelegate, which inherits all of the methods and properties of the NSObject class, and which implements the UIApplicationDelegate protocol.
In your class (.m) file, you will define (with all your code) all of the methods and properties that you declared in your interface file. You include the methods and properties you declared yourself, and from the protocols you implement.
#synthesize is used in a class implementation file (.m) to "synthesize" --- that is, automatically create the code for --- all the properties you declared in your interface (.h) file. Since properties normally just need basic accessors (a "getter" that just returns the current value, and a "setter" that just sets the current value), using #synthesize is a shortcut to let the compiler create the variable to store the value, the getter method, and the setter method for you automatically.
Xcode = An IDE (Integrated Development Environment)
Objective-C = A Language
Cocoa Touch, Media FrameWork, Core FrameWork = Frameworks used in developing for iOS
I'd highly recommend starting by learning Objective-C. At least with a primer first:
https://developer.apple.com/library/ios/#referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/_index.html
There's a wealth of tutorials and videos available from Apple for developers you might want to start on the developer portal.

Resources