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

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.

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.

Meaning of the angle brackets in Objective-C?

Even though the question is quite wide I am actually curious regarding one case I sow recently while using the Realm library. As I previously used the protocols(delegate) on many occasions and also imported classes using <>. And now this is the line the code I don't completely understand or don't understand at all if I am mistaking:
#property (nonatomic, strong) RLMArray <ExerciseLog *><ExerciseLog> * exerciseLogs;
I suppose that the second part of the line <ExerciseLog> * exerciseLogs is used to ensure that exerciseLogs may be an instance of any ExerciseLog that conforms to the ExerciseLog protocol, is my assumption correct?
Or simple said if the user send a different object then the expected one, the app won't crash, and that a default value will be assigned.
And this part I am guessing, the is some sort of safe casting so that the returned object confirms to the ExerciseLog.
A combination of Obj-C protocol conformance and generics. RLMArray is declared as
#interface RLMArray < RLMObjectType : RLMObject * > : NSObject<RLMCollection,NSFastEnumeration>
it has one generic argument. That's the <ExerciseLog *>.
The second part <ExerciseLog> is conformance to protocol of the given type.
By the way, that protocol is declared using RLM_ARRAY_TYPE macro. The code seems to be a bit complicated but it was probably an older way to enforce element type for arrays (RLMArray<protocolX> is not assignable to RLMArray<protocolY>).
Quoting the documentation:
Unlike an NSArray, RLMArrays hold a single type, specified by the objectClassName property. This is referred to in these docs as the “type” of the array.
When declaring an RLMArray property, the type must be marked as conforming to a protocol by the same name as the objects it should contain (see the RLM_ARRAY_TYPE macro). RLMArray properties can also use Objective-C generics if available. For example:
The angle brackets in a class interface definition indicates the protocols that your class is conforming to.
A protocol is almost like an interface in Java or C#, with the addition that methods in an Objective-C protocol can be optional.
Additionaly in Objective-C you can declare a variable, argument or instance variable to conform to several protocols as well. Example
NSObject *myVariable;
In this case the class must be NSObject or a subclass (only NSProxy and its subclasses would fail), and it must also conform to both NSCoding and UITableViewDelegate protocols.
In Java or C# this would only be possible by actually declaring said class.

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.

Undeclared Methods vs Categories in Objective-C

Imagine I have define a class MyClass as follows:
The class interface file:
#import <Foundation/Foundation.h>
#interface MyClass : NSObject
#property (nonatomic) NSString *myProperty;
- (void)myPublicMethod;
#end
The class implementation file using categories:
#import "MyClass.h"
#interface MyClass (MyCategory)
- (void)myPrivateMethod;
#end
#implementation MyClass
- (void)myPublicMethod {
NSLog(#"myPublicMethod was called!");
[self myPrivateMethod];
}
- (void)myPrivateMethod {
NSLog(#"myPrivateMethod was called!");
}
#end
An alternative class implementation file NOT using categories:
#import "MyClass.h"
# implementation MyClass
- (void)myPublicMethod {
NSLog(#"myPublicMethod was called!");
[self myPrivateMethod];
}
- (void)myPrivateMethod {
NSLog(#"myPrivateMethod was called!");
}
#end
Was hoping someone could explain the difference between the two implementation file approaches.
Is it the case that using categories means the "private" methods are inherited by any subclasses of MyClass and not using categories means the "private" methods are not inherited by any subclasses?
All methods that exist on a class are always inherited and are callable by anyone regardless of how you declare them. The main difference is whether anybody knows about them. There was also a historic need to declare things before use which leads to internal forward declarations in older and old-style code.
A category is used to add methods to an existing class. A common use is to extend the functionality of one of the existing classes. For example you might implement:
#interface NSURL (HTTPQueryParameters)
- (NSDictionary *)httpQueryParameters;
#end
So from then on you've given NSURL itself the knowledge required to parse HTTP protocol query parameters. It's often the correct factoring to add functionality directly to classes you don't have the source for.
Objective-C used to follow the C rule that methods had knowledge only of those methods that had preceded them within the compilation unit. So to be able to call a method that appeared later in the source file you'd need a forward declaration. If you didn't want to publish that method for the world to see you could achieve that with a category or a class extension (which for this purpose is just an unnamed category).
Nowadays Objective-C methods can call any method that is defined anywhere within the compilation unit, including subsequently in the same source file. It's therefore now normal not to collect up your unpublished methods into a category or an extension just for the benefit of the compiler.
That leaves categories for:
adding functionality to existing classes; and
segmenting your classes if they become very large;
Class extensions are now primarily for:
declaring #propertys without publishing them.
In Objective-C any method call can be sent to any object — objects are dynamically typed. So there's a mapping table in memory at runtime for every class from method name to implementation. The lookup process is to see whether the method is implemented in the class dispatched to. If not then dispatch to the superclass. An exception will be raised if the runtime runs out of superclasses.
The declaration of the method in a category #interface only serves to expose the method to users of the class, including -- as you mentioned in your comment -- subclasses.
(It would be much more usual to use a class extension (sometimes called an "anonymous category") declare a method that you're defining in the main implementation block. Actually, I'm not 100% sure what the interaction is between your category declaration and the main block definition -- I wouldn't have been surprised if it didn't compile, but it does.)
Thus, the only difference between your two examples is that the declaration allows you to create a private header in a situation where you want your own subclasses to access this method, but have framework users who you want to restrict.

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