Protocol versus Category

后端 未结 7 1578
忘了有多久
忘了有多久 2020-12-12 14:09

Can anyone explain the differences between Protocols and Categories in Objective-C? When do you use one over the other?

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 14:41

    Protocols are contracts to implement the specified methods. Any object that conforms to a protocol agrees to provide implementations for those methods. A good use of a protocol would be to define a set of callback methods for a delegate (where the delegate must respond to all methods).

    Categories provide the ability to extend a current object by adding methods to it (class or instance methods). A good use for a category would be extending the NSString class to add functionality that wasn't there before, such as adding a method to create a new string that converts the receiver into 1337 5P34K.

    NSString *test = @"Leet speak";
    NSString *leet = [test stringByConvertingToLeet];
    

提交回复
热议问题