ios常用的三种传值方式

总结我项目中常用的三种传值方式

近期在研究Python,公司正好有Python项目,对于自己来说也算是横向发展

1:Block传值
场景:比如在同一个页面(A)点击了类型,弹出新的页面(B),这时候需要获取新页面点击的是哪个类型值,,所以就需要新页面将点击的值传递到该页面进行数据操作

这里写图片描述
1:在B的.h文件中定义Block属性

@property(nonatomic,copy)void (^returnPerson)(NSString * persontext);

2: 在B的.m文件中设置属性值

 self.returnPerson(item.code);

3:在A中现实block person值就是B类中的item.code

  ["B对象" setReturnPerson:^(NSString * person) {

 }];

2:代理传值
场景:在A页面点击右边按钮,弹出一个列表页面B,点击B中某个值,刷新A页面数据
这里写图片描述

1:在B的.h文件中定义代理方法

@protocol TopChangViewDelegate <NSObject>
@optional
- (void)selectWithIndex:(NSInteger)index andTitle:(CityModel *)title;
@end
@interface  B类: UIView
@property (nonatomic, weak) id<TopChangViewDelegate> delegate;
@end

2:在B的.m文件中实现代理方法 在点击B中某个值触发的方法中写

 if ([self.delegate respondsToSelector:@selector(selectWithIndex:andTitle:)]) {

        [self.delegate selectWithIndex:“角标” andTitle:@“值”];
   }

3:在A的.m文件中实现

B类 *topContianerView = [[B类 alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
      topContianerView.delegate = self;

实现代理方法 刷新

- (void)selectWithIndex:(NSInteger)index andTitle:(CityModel*)title{

    NSLog(@"选择的是第几个%ld   %@",index,title);

}

3:通知传值
场景是上述一致
1:在B的.m文件 发送需要传递的数据

[[NSNotificationCenter defaultCenter] postNotificationName:@"SelectTagNotification" object:nil userInfo:@{@"tagStr":self.itemtag1,@"tagStr1":self.itemtag2,@"tagStr2":self.itemtag3}];

2:在A的.m文件 接受传递过来的数据

  [[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectTag:) name:@"SelectTagNotification" object:nil];

//实现定义方法即可

-(void)selectTag:(NSNotification*)noty{
// not就是传递过来的数据
 NSDictionary * not = noty.userInfo;
}

3:在A的.m文件 需要remove通知

-(void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值