ios block传值

时间:2025-01-29 14:11:11

ios里的block 可以理解为c++里的函数指针, 我觉得也有点儿像java里面的内部类之类的东西。

block可以代替delegate完成回调工作。

只需要把block当成地址传来传去就行了。

下面把某位仁兄的代码贴出来


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

#import <UIKit/>

@interface MainView : UIViewController
{
    IBOutlet UIButton* btn;
    IBOutlet UILabel* labShow;
}
-(IBAction)push:(id)sender;
@end


 
#import ""
#import ""

@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:Block_copy(^(NSString *str){
        NSLog(@"%@",str);
         = str;
    })];
    [ pushViewController:s  animated:YES];
    [s release];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
}

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

@end


 
#import <UIKit/>
typedef void (^MyBlock)(NSString *);

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


 
#import ""

@implementation SecondView

-(id)initwithBlock:(MyBlock)str
{
    self = [super init];
    if(self)
    {   
        my = str;
    }
    return self;
}
-(IBAction)back:(id)sender
{
    NSString* s = ;
    if(my)
    {
        my(s);
    }
    [ 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







关键点:

1.执行点击事件会出发下面方法,切换到SecondView界面,并且将块元素(函数指针)传入SecondeView

-(IBAction)push:(id)sender
{
    SecondView *s = [[SecondView alloc] initwithBlock:Block_copy(^(NSString *str){
        NSLog(@"%@",str);
         = str;
    })];
    [ pushViewController:s  animated:YES];
    [s release];
}

2.在secondeView中:
typedef void (^MyBlock)(NSString *);
 MyBlock my;
-(id)initwithBlock:(MyBlock)str
{
    self = [super init];
    if(self)
    {   
        my = str;
    }
    return self;
}


initWithBlock方法被调用,并且将块元素保存到my(函数地址)

3.在SecondView中执行点击事件,会触发下面
-(IBAction)back:(id)sender
{
    NSString* s = ;
    if(my)
    {
        my(s);
    }
    [ popViewControllerAnimated:YES];
}

这个方法拿着块元素(函数指针),并且将参数s传入块元素。



4.下面就是关键:
   my会根据块元素的地址,找到块元素的实现部分,也就是在MainView中最初传入的block_copy那里异步执行块实现部分。

这个过程,是不是代理干的事情,或者钩子,或者回调,我觉得这都是一回事。