iOS 不同场景/页面下数据传递方法

记录下 iOS 不同场景/页面下数据传递常用的方法


一、使用属性

最简单常用的方法之一,用于从上到下的顺序,比如 A >> B 时,传递A的数据到B。

OtherController *otherController = [OtherController new];
otherController.stringData = tfData.text;
[self.navigationController pushViewController:otherController animated:YES];


二、使用 Protocol 协议

用于从下到上的顺序,比如 A >> B,再从 B back A 时,B的数据回传到A中。

.h 协议

#import <Foundation/Foundation.h>

/** 协议 */
@protocol OtherDetegate <NSObject>

@required // 必须实现的方法

/**
 * 返回
 * @param backString 返回带的数据
 */
- (void) backToFirst:(NSString *) backString;

@optional // 可选实现的方法

@end


B.h

/** 协议 */
@property (nonatomic, assign) id<OtherDetegate> otherDetegate;

B.m

// 使用协议中的方法回传数据
if (self.otherDetegate) {
        [self.otherDetegate backToFirst:tfOther.text];
}


A.h 

实现 OtherDetegate 协议


A.m

B *b = [B new];
b.otherDetegate = self;
[self.navigationController b animated:YES];

// 实现协议中的方法
/** 返回待来的数据 */
- (void) backToFirst:(NSString *)backString {
    tfData.text = backString;
}

三、使用 Notification Center 消息通知中心

可以用于跨场景的数据传递,比如 A 点击按钮,通知 C 开始下载。

通知中心可以同时向多个观察者传递数据

A.m

/** 发送消息通知 */
- (void) btnNotificationClick {
    NSDictionary *dictData = @{NOTIFICATION_KEY:tfOther.text};
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_OTHER object:self userInfo:dictData];
    
}

C.m

- (void)viewDidLoad {
    [super viewDidLoad];
    
    ......
    
    [self addObserverToNotification];
}

- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

.......

/** 添加通知消息监听 */
- (void) addObserverToNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showNotificationCenter:) name:NOTIFICATION_OTHER object:nil];
}

/** 显示通知内容 */
- (void) showNotificationCenter:(NSNotification *)notification {
    NSDictionary *dict = notification.userInfo;
    
    NSLog(@"通知内容:%@", [dict objectForKey:NOTIFICATION_KEY]);
    
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS 开发中,页面之间的跳转和数据传递通常使用以下方法: 1. 使用故事板(Storyboard):通过故事板可以直观地管理应用的界面和页面之间的跳转关系。在故事板中,你可以创建视图控制器(View Controller)之间的连线,以定义页面之间的跳转关系。你可以使用 Interface Builder 设置跳转时传递数据。 2. 使用编程方式:如果你不使用故事板,也可以使用编程方式进行页面跳转。在源代码中,你可以创建新的视图控制器实例,并使用导航控制器(Navigation Controller)或模态弹出(Modal Presentation)等方式进行页面跳转。同样地,你可以通过代码设置传递数据。 3. 数据传递:在页面之间传递数据,最常见的方法是使用属性(Property)或参数(Parameter)。你可以在目标视图控制器中定义公开的属性或参数,然后在源视图控制器中设置其值。当目标视图控制器加载时,就可以获取传递过来的数据。 4. 代理模式:如果需要在页面之间进行双向数据传递或回调操作,可以使用代理模式。通过定义代理协议(Delegate Protocol)和代理对象(Delegate Object),源视图控制器可以将自己设置为目标视图控制器的代理,并实现相应的代理方法来处理数据传递或回调操作。 这些是常见的 iOS 页面跳转和数据传递方法,具体使用哪种方法取决于你的应用需求和开发方式。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值