您的位置:首页 > 移动开发 > IOS开发

iOS 传值方法(属性传值、代理传值、Block、通知、单例)

2016-06-03 17:25 344 查看
简单的介绍一下几个传值方式

1、属性传值

ExampleViewController.h

#import "ExampleViewController.h"

@interface ExampleViewController :UIViewController

@property(nonatomic,strong)NSString*testString;

@end


ExampleViewController.m

@implementation ExampleViewController

@synthesize testString;


在传值的时候可以这样写

-(void)sendAction{

ExampleViewController*newExample=[[ExampleViewControlleralloc]init];

newExample.testString=@"test";

[selfpresentViewController:newExampleanimated:YEScompletion:nil];

}


2.代理传值

在这里我们用到两个控制器FirstViewCtr和SecondViewCtr,目的是在第二个页面中输入字符串,然后在第一个页面中显示出来。

首先,我们在SecondViewCtr.h里声明代理以及代理方法

#import <UIKit/UIKit.h>

#import"BaseViewController.h"

@protocol SecondDelegate<NSObject>

-(void)showResultWithString:(NSString*)string;

@end

@interfaceSecondViewCtr :BaseViewController

@property(nonatomic,weak)id<SecondDelegate>delegate;

@end


然后在SecondView.m中实现点击传值

-(void)buttonPressedAction{
if(self.delegate&&[self.delegate respondsToSelector:@selector(showResoutWithString:)]) {

[self.delegate showResoutWithString:secondText.text];

}
[self.navigationControllerpopViewControllerAnimated:YES];

}


这一步完成之后,我们要在第一个页面FirstViewCtr.h中使用代理

FirstViewCtr.h

#import<UIKit/UIKit.h>

#import"BaseViewController.h"

#import"SecondViewCtr.h"

@interfaceFirstViewCtr :BaseViewController<SecondDelegate>{

}

@end


在FirstViewCtr.m中实现响应代理的方法,这个方法是SecondViewCtr.h中代理声明的那个方法

-(void)showResoutWithString:(NSString*)string{

firstText.text=string;

}


3.Block传值

简单的实现一下。

首先,我们在First.h中定义一下

typedef void (^MyBlock)(NSString *getString);//定义声明一个block,起个名字MyBlock

@interface First : UIViewController

- (void)getBlockString:(MyBlock)block;//block模块

@end


在First.m中,我们实现一下block模块

- (void)getBlockString:(MyBlock)block{

block(@"Test");

}


然后在需要使用数据的地方或者别的页面调用

[[[First alloc]init]getBlockString:^(NSString*string){

NSLog(@"%@",string);//string就是传过来的@“Test”

}];


4.通知

新建一个通知

[[NSNotificationCenterdefaultCenter]postNotification:[NSNotificationnotificationWithName:@"test"object:niluserInfo:@{@"test":@1}]];


在需要接收通知的地方注册通知

[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(tongzhi:)name:@"test"object:nil];


响应通知的方法

- (void)tongzhi:(NSNotification*)text{

NSLog(@"%@",text.userInfo[@"test"]);

NSLog(@"-----接收到通知------");

}


5.单例

我们定义一个工具类

UserEntity.h

@interface UserEntity :NSObject

+(UserEntity* )getInfo;

@property(nonatomic,strong)NSString*userName;

@end


UserEntity.m

@implementationUserEntity

+(UserEntity* )getInfo{

staticdispatch_once_t pred;

static UserEntity *currentUser;

dispatch_once(&pred, ^{

currentUser = [[UserEntity alloc]init];

});

return currentUser;

}

@synthesize userName;

@end


然后在需要的地方给单例赋值

[[UserEntity getInfo].userName=@"test"];


需要用到值的地方取出来

NSString *name=[UserEntity getInfo].userName;


Demo下载地址
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息