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
343 views
in Technique[技术] by (71.8m points)

iphone - Objective-c - Purpose of categories and protocols

I've been reading up on Objective-c Protocols and Categories and both seem rather pointless to me. They're both used for adding things to the program in some funny way instead of just manually adding it.

I might be convinced to see the purpose of the protocol being so that you can check the type of id's, but that's really about it. I see no other real use for them.

As for categories, I really don't see why you wouldn't just add them to the code. Why do you need to manually specify methods in a category that you're then gonna implement as opposed to just doing it normally? Is it that you might wanna make a "subclass" but with slight modifications? Why not just make a subclass?

I really don't see the purpose of either of these, I hope someone can tell me their real use =/

Thanks in advance, Christian

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Categories are to add methods to classes whose source is unavailable to you, such as all the Apple classes (those starting with NS, CG, CA, etc.), without needing to subclass them.

The purpose of protocols is to define methods that classes adhering to that protocol have to implement. In Java, those are called interfaces. The purpose is to codify similarities between classes that are not siblings (subclasses of the same superclass). Suppose you have a class Chair and a class Petrol. These don't have a lot in common, except that they both adhere to the flammable protocol, which requires them to have certain methods, such as specificEnergy and flamingPoint.

Now your Fire class can have a method addFlammableMaterial:(id <flammable>)material.

Protocols are often used to declare that instances of certain classes can be delegates for certain other instances. You can declare your view controller to act as the data source to a UITableView by declaring it to conform to the UITableViewDataSource protocol, which means your viewController guarantees that it implements the required methods of that protocol, and the tableView can rest safely because it can trust the VC to be its data source.


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

...