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];
}

猜你喜欢

转载自blog.csdn.net/JSON_6/article/details/78920719
今日推荐