0
@protocol I <NSObject>
-(void) f;
-(void) g;
@end

@interface C : NSObject <I> 
{
    id<I> i;
}
-(void) toA;
-(void) toB;
@end

I am using this code, Here I am using a protocol I, I want to know what is the meaning of ( id< I > i ) and working of this.

Lebyrt
  • 1,376
  • 1
  • 9
  • 18
Anshuman Mishra
  • 189
  • 1
  • 8

6 Answers6

2

Declaration:

MyClass<MyProtocol> * myVar;

means that class of myVar is one of MyClass descendants and additionaly implements methods of MyProtocol protocol. Read more about protocols here.

And in your code

id<I> i;

means that "i" is of id type - i.e. it can be object of any class (read about id here), but is also conforms to protocol "I".

In you sample class of your "i" must implement

-(void) f;
-(void) g;

methods.

And you can use expressions like:

[i f];
[i g];
Vladimir
  • 7,670
  • 8
  • 28
  • 42
0

It means that the iVar i of any type (thus id), conforms to protocol I.

Bartosz Ciechanowski
  • 10,293
  • 5
  • 45
  • 60
  • Here: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html – Cyrille Oct 13 '11 at 07:26
0

You declared i as an Objective-C object of type id that conforms to your protocol I.

Read more about it here: http://unixjunkie.blogspot.com/2008/03/id-vs-nsobject-vs-id.html

BojanG
  • 1,872
  • 1
  • 15
  • 23
0

i is an object. It could be any class, as long as that class conforms to the protocol I. That means that class has instance methods f and g that take no arguments and return nothing. That class also must formally adopt protocol I. Class C actually adopts protocol I. Inside a method of class C you could write:

i = self;

Though that might not usually be very useful. More likely some other class adopts protocol I too, or at least you would assign a different instance of C to i, like

i = [[C alloc] init];
morningstar
  • 8,952
  • 6
  • 31
  • 42
0

id refers to a variable that adheres to the protocol I. In this case, you would then need i to be be a variable whose class implements protocol I.

LAW
  • 1,099
  • 3
  • 12
  • 20
0

You probably want to read up on the delegates here: How to use custom delegates in Objective-C

The id i is your delegate property. When you use it. You can call one of the delegate methods you described in your protocol, aka method f and g. In the class that comforms to the protocol you given shape to these methods.

Community
  • 1
  • 1
Totumus Maximus
  • 7,543
  • 6
  • 45
  • 69