码迷,mamicode.com
首页 > 移动开发 > 详细

iOS中使用block传值

时间:2014-05-10 07:43:17      阅读:403      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   tar   

转自:http://blog.sina.com.cn/s/blog_60b45f230100yiaf.html

用此方法传值可以替代委托了。具体例子:

MainView.h
bubuko.com,布布扣
#import <UIKit/UIKit.h>

@interface MainView : UIViewController
{
    IBOutlet UIButton* btn;
    IBOutlet UILabel* labShow;
}
-(IBAction)push:(id)sender;
@end
bubuko.com,布布扣

 

MainView.m

bubuko.com,布布扣
#import "MainView.h"
#import "SecondView.h"

@implementation MainView

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
}
-(IBAction)push:(id)sender
{
    SecondView *s = [[SecondView alloc] initwithBlock:^(NSString *str){
        NSLog(@"%@",str);
        labShow.text = str;
    }];
    [self.navigationController pushViewController:s  animated:YES];
    [s release];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
bubuko.com,布布扣

 

SecondView.h
bubuko.com,布布扣
#import <UIKit/UIKit.h>
typedef void (^MyBlock)(NSString *);

@interface SecondView : UIViewController
{
    IBOutlet UITextField* txtView;
    MyBlock my;
}
-(IBAction)back:(id)sender;
-(id)initwithBlock:(MyBlock)str;
@end
bubuko.com,布布扣

 

SecondView.m
bubuko.com,布布扣
#import "SecondView.h"

@implementation SecondView

-(id)initwithBlock:(MyBlock)str
{
    self = [super init];
    if(self)
    {   
        my = str;
    }
    return self;
}
-(IBAction)back:(id)sender
{
    NSString* s = txtView.text;
    if(my)
    {
        my(s);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
-(void)dealloc{
    Block_release(my);
    [super dealloc];
    
}
#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
bubuko.com,布布扣

 

界面:
bubuko.com,布布扣

bubuko.com,布布扣

bubuko.com,布布扣

iOS中使用block传值,布布扣,bubuko.com

iOS中使用block传值

标签:style   blog   class   code   java   tar   

原文地址:http://www.cnblogs.com/wangpei/p/3719284.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!