Understanding @Protocols in Objective-C

前端 未结 5 1042
一整个雨季
一整个雨季 2020-12-11 12:38

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\" b

相关标签:
5条回答
  • 2020-12-11 13:01

    Like @conmulligan says Objective-C uses protocols to make classes talk to each other.

    Its one of many ways to communicate between classes.

    But protocols is necessarily a bad way.

    I use protocols if I was to create a re-usable object, that is usually used for many projects.

    So I create protocols to make my code easy to maintain.

    0 讨论(0)
  • 2020-12-11 13:03

    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.

    0 讨论(0)
  • 2020-12-11 13:07

    One word, delegates.
    Objective-c uses delegates all over the place to allow classes to talk to each other.
    To see an example see UITableViewDelegate Protocol
    That's not the only place @protocol is used, but it's probably the most common use for it.

    0 讨论(0)
  • 2020-12-11 13:19

    Protocols are better versions of callback functions in C. Protocols are useful constructs when you want to implement MVC architecture yourself. The Views need to be notified when Model changes,You can use protocols to notify appropriate events to Observers.

    0 讨论(0)
  • 2020-12-11 13:20

    You could have a class that is a UIViewController, and it implements several protocols, such as UITableViewDelegate, UITableViewDataSource. A class can do more than one thing.

    0 讨论(0)
提交回复
热议问题