What does < > mean / represent in a class interface? - objective-c

I am sure I have read this somewhere, Can anyone tell me what the < > represent in the following interface?
#interface GameFinder : NSObject <NSNetServiceBrowserDelegate>
#end
is NSObject adopting <NSNetServiceBrowserDelegate> ?
EDIT
One thing that is confusing me ...
in the example I have.The interface shows NSNetServiceBrowserDelegate
#interface ITunesFinder : NSObject <NSNetServiceBrowserDelegate>
#end
but the implementation shows netServiceBrowser, are these one in the same?
#implementation ITunesFinder
-(void) netServiceBrowser: (NSNetServiceBrowser *) browser
didFindService: (NSNetService *) service
moreComing: (BOOL) moreComing {
gary

The angle brackets denote Protocols that this class meets. There are details on Protocols int the Objective-C Wikipedia article that may help clear up some things for you. Protocols contain both required and optional routines that your class could supply. In the latter case if the routine is not implemented by your class a default implementation/behavior is used instead.

< > represent a protocol (or list of protocols) to which a class conforms. An Objective-C protocol is like an interface in Java: it's a list of methods that the conforming class must implement.

The angle brackets in an interface declaration denote the list of Objective-C protocols that the interface implements. In this case, that GameFinder conforms to the NSNetServiceBrowserDelegate protocol. The Objective-C Language Reference has a full section on protocols (and is a reference you should keep handy in general while learning Objective-C). Basically, a Protocol is an interface that describes the methods a class must implement to conform to that protocol. Classe interfaces may declare, using the angle bracket notation, that they conform to (implement) a protocol. The compiler will check protocol conformance if you provide protocol information in type declarations:
#interface Foo <Bar>
...
- (void)methodRequiringBar:(id<Bar>)arg;
#end
#interface Foo2 <Baz>
...
#end
id<Bar> v = [[Foo alloc] init]; //OK
id<Baz> v = [[Foo alloc] init]; //warning
[v methodRequiringBar:[[Foo2 alloc] init]]; //warning
The compiler will also warn you if a class interface declares conformance to a protocol but not all of the required methods in that protocol are implemented by the class' implementation:
#protocol Bar
#required
- (void)requiredMethod;
#optional
- (void)optionalMethod;
#end
#interface Foo <Bar>
...
#end
#implementation Foo
- (void)optionalMethod {
...
}
#end
will give a warning that the Bar protocol is not fully implemented.

NSNetServiceBrowser is a class. NSNetServiceBrowserDelegate is a protocol specifying what methods an NSNetServiceBrowser's delegate must implement.

Related

Objective C Protocols and Inheritance

Ok, there are several questions with "Protocol" and "Inheritance" but I can't really find the answer to my question. I have a class with a protocol. For example:
#class SomeClass;
#protocol SomeDelegate <NSObject>
#optional
-(void) someMethod;
#end
#interface SomeClass : NSObject
{
id<SomeDelegate> delegate;
}
#property id<SomeDelegate> delegate;
-(void) thisDoesStuff;
#end
Then I have a different class whose object will be a delegate of a SomeClass object:
#interface DiffClass: SomeClass<SomeDelegate>
// This method will conform to the one specified on the protocol
-(void) someMethod;
#end
My question is, does DiffClass inherit from SomeClass? I'm considering the syntax in Objective C for inheritance:
#interface ClassA : SuperClassOfClassA
Where, in the above, ClassA inherits from SuperClassOfClassA.
Additionally, in Objective C, is it possible to inherit from one class and adopt a protocol from a different class? I guess what I'm trying to get at is if it's possible that two objects are able to communicate to each other through delegates without having to inherit from that protocol's class (I hope I'm making sense).
Thanks in advance!
In practice, your code would be very strange.
First, you don't have a class with a protocol. You have a protocol named SomeDelegate. Then you have a class SomeClass, which is unrelated to the protocol. Well, it has an instance variable that supports SomeDelegate, but that has nothing to do with the protocol.
Then you create a class that is both a subclass of SomeClass, and supports the SomeDelegate protocol. That's unusual. I mean DiffClass both supports the protocol itself, and has a delegate supporting the protocol. That's a bit strange.
Nevertheless, DiffClass is a subclass of SomeClass, and you promised that it supports the protocol SomeDelegate, so that's fine.
But really: A protocol doesn't belong to a class. I don't know what made you think that, but you have to remove that from your brain immediately. A protocol is a totally different thing and totally independent from a class. It's a set of requirements that any class may or may not fulfil. It exists independent of any class. Because a protocol is a set of requirements, a class can support that protocol by claiming it does (adding ) and by adding the required methods.
To answer your first question, DiffClass does inherit from SomeClass as you have it written. But it doesn't need to inherit from SomeClass. I'll be a bit more thorough below.
A protocol is a declaration of methods (and properties) that a class adopts. It does not have to be related to a class, although it often is for the delegation pattern.
For example, you could have a header that just declares a protocol. Let's call the file NewProtocol.h
#protocol NewProtocol<NSObject>
#optional
- (void)newMethod;
#end
Then any class can adopt that protocol. With your example above, this could be DiffClass. You do not need to declare the methods from NewProtocol again in the class interface.
// You would need to import NewProtocol.h
// Note that this does NOT inherit from SomeClass.
#interface DiffClass : NSObject<NewProtocol>
#end
Then the implementation of DiffClass would need to provide the declared protocol methods.
#implementation DiffClass
- (void)newMethod {
// Do stuff.
}
#end
Then SomeClass could have a property for the declared protocol above.
#interface SomeClass : NSObject
// Often you will want weak for delegates as they can cause retain cycles otherwise.
#property(nonatomic, weak) id<NewProtocol> thingThatImplementsNewProtocol;
-(void) thisDoesStuff;
#end
DiffClass does now NOT inherit from SomeClass but can be used to communicate with SomeClass. You could declare a second protocol that SomeClass adopts and a property on DiffClass to have two way communication.
Often the protocol are declared in the same header file as a class for simplicity because they are intended as delegates for specific objects.
Answer to the question 1: with the statement
#interface DiffClass: SomeClass<SomeDelegate>
The DiffClass inherits from SomeClass and also conforms the protocol(interface) SomeDelegate.
Answer to the question 2: In Objc you can inherit only from one parent class (multiple inheritance wont be supported) but you can conform as many as protocols (interfaces) you want.
Lets take and example of an drawing App. Shape is a parent class and RectangleShape, LineSahpe, TextShape, CircleShape are the children from Shape class. All four children are inheriting from their parent Shape. But you need to move the shape except LineShape. There you can have protocol (interface) as Movable. That you can do so.
#protocol Movable <NSObject>
#end
#interface Shape : NSObject
#end
#interface RectangleShape : Shape <Movable>
#end
#interface LineSahpe : Shape // cannot be moved, just for an example.
#end
#interface TextShape : Shape <Movable>
#end
#interface CircleShape : Shape <Movable>
#end
You can have a method for the protocol like this to move all Shaped which are conforming Movable protocol (interface).
- (void)move:(id <Movable>)movableShape {
}
You can implement a communication instead of moving shapes. Protocols are really useful during advanced programming.
Hope it will help you... please feedback me.

Calling a method defined in a protocol on a class included with forward declaration

Is there a way to tell the compiler that a non-imported class (i.e. forward declaration) adheres to a protocol?
In the example below I want to call a method foo on the class ForwardClass. The class adheres to the MyProtocol protocol, but the compiler won't know that since forward declaration is used.
#protocol MyProtocol <NSObject>
+ (void) foo;
#end
#class ForwardClass; // <-- Forward declaration
#implementation MyClass
- (void) bar
{
[ForwardClass foo]; // <-- This doesn't work!
}
What I was hoping for was to either apply the protocol while declaring the class like so:
#class ForwardClass <MyProtocol>
or to somehow use the protocol while calling the method like so:
[ForwardClass<MyProtocol> foo];
This is not really a big issue since I could just import the class straight away, but it would be nice if it worked since I would only have to import the protocol, and not the whole class.
No. Forward declarations are for situations where you need to know the the class type but don't need to know about its specific implementation (properties and methods for example). In your case you do care about the methods it implements so you need to bring in the header for for ForwardClass.
You could do
Class x = NSClassFromString(#"ForwardClass");
[x foo];
but it is not as pretty

Dependency injection with #protocol?

Can I use a #protocol for interfacing between classes? My main goal is to do some dependency injection like in Java (with interfaces and implements).
I've got the following classes: SignUpServiceImpl (which has an interface called SignUpService) and ServiceHelperImpl (interface is ServiceHelper).
I don't want to hard wire both implementations together so I use a #protocol in ServiceHelper which is implemented by ServiceHelperImpl. Then SignUpServiceImpl is initialized with ServiceHelper like this:
- (id)initWithHelper:(ServiceHelper *)myServiceHelper
Is what I'm trying to accomplish possible? It looks so much easier in Java....
An objc protocol is very similar to a Java interface.
The blocking point for you may be how you expect things are actually tied together -- or protocol syntax.
Declare a protocol:
#protocol ServiceHelperProtocol
- (void)help;
#end
Use it in a class:
#interface SomeClass : NSObject
- (id)initWithServiceHelper:(id<ServiceHelperProtocol>)inServiceHelper;
#end
#implementation SomeClass
- (id)initWithServiceHelper:(id<ServiceHelperProtocol>)inServiceHelper
{
self = [super init];
if (nil != self) {
[inServiceHelper help];
}
return self;
}
#end
MONHelper adopts the protocol:
#interface MONHelper : NSObject < ServiceHelperProtocol >
...
#end
#implementation MONHelper
- (void)help { NSLog(#"helping..."); }
#end
In use:
MONHelper * helper = [MONHelper new];
SomeClass * someClass = [[SomeClass alloc] initWithServiceHelper:helper];
...
To accept an object that conforms to a protocol, your init method should be like this:
- (id)initWithHelper:(id<ServiceHelper>)myServiceHelper
If you want to keep a number of different implementations behind a unified class interface, one way to do this in Objective-C is to create an abstract class SignUpService, then in the init method of SignUpService, instead of returning self you actually return a instance of the class that you want to implement it, so in your case, SignUpServiceImpl.
This is how certain class clusters in Cocoa like NSString work.
Let me know if you need more info.

Is it possible for a class to conform to more than one protocol in objective-c?

Is it possible for a class to conform to more than one protocol in objective-c? If so,
what is the syntax for declaring a class that conforms to more than one protocol?
#interface MyClass : NSObject <Protocol1, Protocol2, Protocol3>
#end
Yes; Just put a comma between each Protocol.
Yes it is possible for a class to conform to multiple protocols. The syntax is as follows:
#interface MyClass : NSObject <Protocol1, Protocol2, Protocol3>
//...Some code here...
#end
A protocol in Objective-C is essentially a list of methods which must be implemented in order for an object or class to be said to be conforming to that protocol. A common example of a class conforming to multiple protocols is a UITableViewController that acts as a UITableViewDataSource and a UITableViewDelegate.
For a UITableViewController example, it might look like this:
#interface MyTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
//...Some code here...
#end
You separate each protocol with a comma, and put it inside of those brackets. When you add those protocols to your interface declaration, you're essentially saying "yes, I'll implement the methods defined by those protocols". Now, go ahead and implement those methods, or the compiler will remind you that you haven't kept your word.

Objective C - How can I create an interface?

I need to be able to create an interface like you create in C# to enforce a group of classes to implement certain methods.
Is this possible in objective c?
You can create a protocol. it would look something like this:
in MyProtocol.h:
#protocol MyProtocol
-(void)myMethod;
-(void)myMethod2;
#end
in MyClass.h
#import "MyProtocol.h"
#interface MyClass : NSObject<MyProtocol>
#end
If you want to receive objects of a given protocol, you can do so like this:
id<MyProtocol> var;
or
NSObject<MyProtocol> *var;
more info here
You declare a "protocol" (Objective-C's interfaces) using
#protocol MyProtocol <BaseProtocol1,...,BaseProtocolN>
//methods and properties
#end
where <BaseProtocol> is optional and indicates that MyProtocol "inherits" BaseProtocol's interface. The NSObject protocol is useful in this context because it allows you to use
#protocol MyProtocol <NSObject>
//...
#end
to indicate (when appropriate) that conforming instances of MyProtocol have the standard NSObject methods as well (e.g. -retain/-release, etc.).
You then declare that a class "conforms" to a protocol:
#interface MyClass : NSObject <MyProtocol,...,OtherProtocols>
{}
#end
And you can test whether an instance conforms to a protocol:
id myInstance = ...; //some object instance
if([myInstance conformsToProtocol:#protocol(MyProtocol)]) {
// myInstance conforms to MyProtocol
}
You can further silence compiler warnings by declaring that a variable holds instances that conform to a protocol (note that Objective-C's dynamic nature prevents the compiler from verifying that contract and you can still get runtime errors by assigning a non-conforming instance to the variable):
id<MyProtocol> o;
In this case, the compiler will complain if you send [o retain] without MyProtocol conforming to the NSObject protocol. You can silence these warnings by declaring MyProtocol as conforming to NSObject as described above or by delcaring o as
NSObject<MyProtocol> o;
Since NSObject is not the only root object in Cocoa (i.e. NSProxy does not inherit from NSObject), it's not necessarily true that all instances conforming to MyProtocol also conform to NSObject. If you know that they do, you can declare MyProtocol as conforming to NSObject.
In the Objective-C world, interfaces are called "Protocols"
According to Apple,
Protocols declare methods that can be implemented by any class. Protocols are useful in at least three situations:
To declare methods that others are expected to implement
To declare the interface to an object while concealing its class
To capture similarities among classes that are not hierarchically related
So, to declare a protocol you can:
#protocol SomeClassProtocol
- (void) do:(int) number something:(id) sender;
- (void) somethingElse;
#end
To implement a protocol , you do:
#interface MyClass : NSObject <Protocol1, Protocol2, ..., ProtocolN>
#end
Check out this link for the official documentation.
Interfaces are called protocols in Objective C
If you go to add a class to your project you will have an option to create it as protocol and you will end up with something like:
#protocol MyProtocol
-(void) DoSomething;
#end