user2348456
user2348456

Reputation: 1

Objective-C Delegate Declaration without a Protocol?

I know I can define a delgate in my .h file as follows:

@property (nonatomic, weak) id <MyClassDelegate> delegate;

and I found this declaration works too:

@property (nonatomic, weak) id delegate;

I use xcode 4.6 and the lastest sdk. My question is: would the compiler automatically look for the "MyClassDelegate" in .h file?

Upvotes: 0

Views: 70

Answers (2)

Reinhard M&#228;nner
Reinhard M&#228;nner

Reputation: 15227

You can have formal delegation (your 1st Version) using a protocol, and informal delegation without a protocol (your 2nd Version). Both are syntactically correct.

Upvotes: 1

Wain
Wain

Reputation: 119031

You can define your delegate instance variable in either way, but the first way is better.

The first way, the compiler will go and find the protocol (you need to import whichever .h file it's defined in) and then it will check that:

  1. anywhere the delegate is set, the instance being set implements the protocol
  2. anywhere you use the delegate, you're calling a known method on it

The second way, the compiler does no checks and leaves everything to run-time.

The protocol doesn't need to be defined in a file with a specific name, it just needs to be defined in the file where you try to use it or the file it is defined in needs to be #imported.

Upvotes: 1

Related Questions