使用@selector模仿代理功能降低代码耦合度

本文介绍了一种使用@selector机制来降低Objective-C中对象间耦合度的方法。通过设置代理及方法选择器,实现了对象间的解耦,使得代码更易于维护。文章通过具体示例展示了如何利用此技术实现这一目标。

使用@selector模仿代理功能降低代码耦合度

 

说明

该模式的好处就是两个产生联系的对象间并没有具体的耦合代码,增删改查均很直观

 

源码

Model

//
//  Model.h
//  SELMethod
//
//  Created by YouXianMing on 15/5/22.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import <Foundation/Foundation.h>


#define SafePerformSelector(Stuff) \
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
Stuff; \
_Pragma("clang diagnostic pop") \
} while (0)


@interface Model : NSObject


/**
 *  属性名字
 */
@property (nonatomic, strong)  NSString  *name;


/**
 *  设置代理与方法
 */
@property (nonatomic, weak) id    delegate;
@property (nonatomic)       SEL   method;


- (void)doSomeThing;


@end
//
//  Model.m
//  SELMethod
//
//  Created by YouXianMing on 15/5/22.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import "Model.h"

@implementation Model

- (void)doSomeThing {
    
    // 执行代理以及方法
    if (_method && _delegate) {
        SafePerformSelector([_delegate performSelector:_method withObject:self]);
    }
}

@end

ViewController

//
//  ViewController.m
//  SELMethod
//
//  Created by YouXianMing on 15/5/22.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import "ViewController.h"
#import "Model.h"

@interface ViewController ()

@property (nonatomic, strong) Model *model;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 初始化对象
    self.model        = [Model new];
    self.model.name   = @"YouXianMing";
    
    // 设置代理与方法
    self.model.method   = @selector(modelValue:);
    self.model.delegate = self;
    
    // 执行操作
    [self.model doSomeThing];
}

- (void)modelValue:(Model *)value {
    NSLog(@"%@", value.name);
}

@end

 

细节

 

转载于:https://www.cnblogs.com/YouXianMing/p/4521491.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值