代理、单例、tableView必写的两个代理方法、block及setter,getter方法

本文介绍了iOS开发中代理模式的实现方式,包括定义代理协议、设置代理属性及其实现方法;同时阐述了单例模式的实现过程,通过dispatch_once确保线程安全。此外还涉及了tableView代理方法、block的使用及setter/getter方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



1.代理
(1)
@protocol ClassNameDelegate <NSObject>
@optional
方法名
@end

@interface
@property (nonatomic, assign) id<ClassNameDelegate> delegate;  
@end

(2)
@protocol requestFinish <NSObject>
-(void) requestFinish:(id) sender;
-(void) requestError:(id) sender;
@end
@interface HttpRequest : NSObject
{
}
@property (nonatomic, assign) id<requestFinish> requestDelegate;
@end
实现:
    if (_requestDelegate && [_requestDelegate respondsToSelector:@selector(requestFinish:)])
    {
        [_requestDelegate requestFinish:reciveData];
    }


2.单例

@interface
+ (instancetype)sharedClassName;
@end

@implementation
(instancetype)sharedClassName {
    static ClassName *className = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
            _className = [ClassName new];
    });
    
    return _className;
}
@end

3.tableView代理方法
@implementation
//     cell 每组几行:
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {   }
//     cell 的内容:
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {   }
@end



4.block
(1)
@interface ViewController : UIViewController
@property (nonatomic, copy) 返回值(^block名)(参数列表);    // 声明
@end

@implementation
self.block名(传参)   // 调用
@end

@implementation
self.block名 = ^(参数列表) {
    // 实现    
}  
@end

(2)block 新类型
typedef void(^ResultBlock) (int,int);
@interface ViewController: UIViewController
// 定义一个block属性,一定使用 copy 特性
@property (nonatomic,copy)ResultBlock block;
@end

@implementation
(void)value:(ResultBlock)block;
@end


5 setter方法
- (void)setName:(NSString *)name {
    _name = name;
}

6 getter方法
- (NSString *)name {
    return _name;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值