Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

iphone - Understanding @Protocols in Objective-C

I am a beginner to programming, and a beginner to Objective-C. I learned basic C and decided to start learning Objective-C. I am reading "Programming in Objective C 2.0" by Steven Kochan. His section on Protocols is vague. He doesn't thoroughly explain WHY someone would want to use protocols in their programs, nor does he give a concrete example with it implemented in a program. He writes: "You can use a protocol to define methods that you want other people who subclass your class to implement." He also says that Protocols are good for sub-classes to be able to implement certain methods, without having to first define the actual methods. He also says protocols can be used across different classes because they are classless.

I know there must be a valid and smart way to implement protocols, but based on what he wrote, I don't see why someone would use protocols instead of just creating a class method outside of the reason that more than one class can adhere to a protocol (I know there are some more good reasons though!). I was wondering if someone could help me understand: how, why and when I would use Protocols in my program in an intelligent way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you've done any kind of object-oriented programming, you probably know protocols as interfaces (they're not identical, but the concept is similar). If not, think of protocols as blueprints.

The main reason why you'd use protocols is so you can use objects without knowing everything about them; all you need to know is that they implement a set of methods. For example, if the classes Business and Person conform to the protocol Contact, which defines the method - (NSString *)phoneNumber, the class AddressBook can call -(NSString *)phoneNumber without knowing whether or not the object is of type Business or Person.

Once you start to learn about Cocoa and delegates, you'll see how powerful and important protocols are.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...