iOS - 6種常見傳值方式比較

常見的6種傳值方式

1.屬性傳值 2.方法傳值 3.代理傳值 4.Block傳值 5.單例傳值 6.通知傳值

1.屬性傳值

1.傳值第一步就得確定傳的屬性類型,然後就定義什麼樣的屬性

2.在控制器跳轉中給屬性賦值

    TwoViewController *two = [[TwoViewController alloc]init];
    two.firstValue = @"ValueToSend";
    [self.navigationController pushViewController:two animated:YES];

2.方法傳值

方法傳值,可以直接將方法與初始化方法合併。
觸發MainViewController的點擊事件並跳轉時,直接通過初始化將值保存。

-(id)initWithValue:(NSString *)value
{
    if (self = [super initWithNibName:nil bundle:nil]) {
        self.firstValue = value;
    }
    return self;
}

3.代理傳值

這種傳值主要用於A進入B,然後B輸入值後傳回給A。
常見於修改個人信息,點擊進入修改界面,修改完之後回到顯示界面,顯示修改後的結果。

 SixViewController *six = [[SixViewController alloc]init];
     six.delegate = self;//把自己設置爲對方的代理
     [self.navigationController pushViewController:six animated:YES];

 [self.delegate changeValue:self.DMTextField.text];//對方要做事,讓自己去做,就改了自己這邊的值
     [self.navigationController popViewControllerAnimated:YES];

4.Block傳值

閉包特性,傳函數過去。
對方之行到這個函數的時候,修改值,就把數值傳過來。

    EightViewController *eight = [[EightViewController alloc]initWithBlock:^(UIColor *color, NSString *name) {
        self.view.backgroundColor = color;
        self.DMlabel.text = name;
    }];
    [self.navigationController pushViewController:eight animated:YES];

    NSArray *array = [NSArray arrayWithObjects:[UIColor yellowColor],[UIColor cyanColor],[UIColor greenColor],[UIColor brownColor], nil];
    self.myBlock([array objectAtIndex:rand() % 4],_DMTextField.text);
    [self.navigationController popViewControllerAnimated:YES];

5.單例傳值

寫個單例。
+ (AppData *)share {
    static AppData *sharedManager =nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedManager = [[self alloc] init];
    });
    return sharedManager;
}
到處取值。
[AppData share].height = 22;

6.通知傳值

(NSNotification *)notification.userInfo可以傳NSDictionary.

註冊接收通知。
    TwelveViewController *twelve = [[TwelveViewController alloc]init];
    [self.navigationController pushViewController:twelve animated:YES];
    //註冊接收通知中心
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //接收通知
    [center addObserver:self selector:@selector(receiveNotification:) name:@"notification" object:nil];

發送通知和數據。
    NSArray *array = [NSArray arrayWithObjects:[UIColor greenColor],[UIColor yellowColor],[UIColor cyanColor],[UIColor purpleColor], nil];
    _dic = @{@"color":[array objectAtIndex:rand() % 4],
             @"text": self.DMTextField.text};
    //註冊通知中心
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //發送通知
    [center postNotificationName:@"notification" object:@"wangdeming" userInfo:_dic];

接收通知裏的數據。
    self.view.backgroundColor = [notification.userInfo valueForKey:@"color"];
    self.DMTextField.text = [notification.userInfo valueForKey:@"text"];
    NSLog(@"%@",notification.object);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章