Things you should pay attention to when writing OC code: protocols and classifications.md

1. Data communication through delegation protocol and data source protocol

(1) Custom protocols need to define protocol methods and protocol attributes, and the attributes must be weak to prevent circular references.

(2) The way to implement a delegate object is to declare a class to comply with the delegation protocol, and then implement the methods in the protocol in the class.

(3) General calls of protocol methods:

    if([_delegate respondsToSelector:@selector(getData)]) {
        [_delegate getData];
    }

But if necessary, you can implement a structure containing bit fields to cache the information about whether the delegate object responds to the relevant protocol method.

@interface WXCEShiViewController (){
    struct {
        unsigned int didRecter : 1;
    }_delegateFlag;
}

@end

@implementation WXCEShiViewController


- (void) setDelegate:(id<wxceshiDelegate>)delegate{
    _delegate = delegate;
    _delegateFlag.didRecter = [delegate respondsToSelector:@selector(getData)];
}

- (void)viewDidLoad {
    [super viewDidLoad];
  	//主要是为了避免重复判断选择器从而影响到性能
    if(_delegateFlag.didRecter) {
        [_delegate getData];
    }
}
2. Logically distribute the implementation code of the class into several categories for easy management.

Use categories to divide implementation code into manageable chunks. Classify methods that should be considered private into a category called Private to hide implementation details.

3. Always prefix the names of third-party classes (plus your own unique embellishments)
4. Do not declare attributes in categories. In addition to class-continuation categories, you can define access methods. Try not to define attributes.
5. Use class-continuation classification to add instance variables to expand internal attributes in this classification.

Compliance protocols are also generally stated in the classification.

Guess you like

Origin blog.csdn.net/weixin_42357849/article/details/122001829