Stunner
Stunner

Reputation: 12204

id and Delegate Usage in Obj-C

I am wondering what the following line of code is doing:

@property (assign, nonatomic) id <CoursePlannerDelegate> delegate;

Namely I am wondering about this portion of the line:

id <CoursePlannerDelegate> delegate;

It also shows up in other places:

@interface CategoryAddViewController : UIViewController {

 UITextField *nameField, *weightField;
 double maxWeight; //The maximum weight that can be allocated to this Category (max value of 100)
 id <CategoryAddDelegate> delegate; //A Course Planner TVC

}

Upvotes: 6

Views: 2514

Answers (2)

makdad
makdad

Reputation: 6450

JustSid's answer is spot-on, but just a bit more clarification:

Compared to other OO languages, Objective-C lacks interfaces. Instead, Objective-C uses protocols, marked by the @protocol directive.

The id data type is an anonymous object. It's an Objective-C object -- that much is certain to the compiler. The compiler knows how much space to reserve for a pointer to the object, but it doesn't know at compile time if it's an NSString, a UIViewController, or what.

So, when you use the id type, you can specify (in angle brackets) a protocol that that anonymous object should adhere to.

In your code above, when compiling, the compiler will check any object you set to the delegate of CategoryAddViewController and double-check that you've implemented any required methods defined in the protocol.

Summed up, using the angle brackets when you use the id type will help the compiler tell you when you're doing something stupid.

All of this is for compile time -- if you need to be 100% paranoid at run time as well, you can use conformsToProtocol:@protocol(foo) to test for compliance (I believe this is a method on any NSObject).

Upvotes: 13

JustSid
JustSid

Reputation: 25318

It makes sure that you pass an Objective-C object that conforms to the given protocol. Thats it, if it doesn't, the compiler will throw a warning but nothing more.

Upvotes: 4

Related Questions