iOS protocol delegate 编程规范

来源:互联网 发布:mathematica 11 mac 编辑:程序博客网 时间:2024/05/21 15:43

接手一个项目,发现有一个有一个@optional的delegate函数内容是空的,就随手删掉了,结果程序崩溃了……

引以为戒吧,以下是正确的@optional delegate函数调用方式:

MyObject.h

////  MyObject.h//  delegateTest////  Created by waterforest on 14-9-16.//  Copyright (c) 2014年 sohu-inc. All rights reserved.//#import <Foundation/Foundation.h>@class MyObject;@protocol MyObjectDelegate <NSObject>@required- (void)c:(MyObject *)object;@optional- (void)d:(MyObject *)object;@end@interface MyObject : NSObject@property(nonatomic, assign) id<MyObjectDelegate> delegate;- (void)a;@end

MyObject.m

////  MyObject.m//  delegateTest////  Created by waterforest on 14-9-16.//  Copyright (c) 2014年 sohu-inc. All rights reserved.//#import "MyObject.h"@implementation MyObject- (void)a{    [self.delegate c:self];        if ([self.delegate respondsToSelector:@selector(d:)]) {// 这才叫Opthional        [self.delegate d:self];    }}@end


0 0
原创粉丝点击