IOS中的Block在C++中的运用

1.IOS中block基本demo

A视图->B视图,B视图传值给A视图

A视图的代码片段

- (IBAction)action2OtherView:(id)sender
{
	MyView *myView = [[MyView alloc] init];
	myView.func = ^(int x,int y)
	{
		int xy = myView.number;
		NSLog(@"xy->%d",xy);
		[myView removeFromSuperview];
		return 0;
	};
	[self.view addSubview: myView];
	[myView release];
}



B视图:

.h文件:

@interface MyView : UIView

@property(assign,nonatomic) int number;
@property(copy,nonatomic) int (^func)(int x,int y);
@property(retain, nonatomic) UIButton* button;
@end

.m文件:
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
	[self setFrame:CGRectMake(100, 100, 300, 200)];
	self.backgroundColor = [UIColor yellowColor];
        // Initialization code
	self.number = 5;
		
	self.button  = [UIButton buttonWithType : UIButtonTypeRoundedRect];
	[self.button setBackgroundColor : [UIColor blueColor]];
	[self.button setFrame : CGRectMake(50, 50, 50, 50)];
		
	[self.button addTarget:self action:@selector(showBack) forControlEvents:UIControlEventTouchUpInside];
	[self addSubview:self.button];
    }
    return self;
}


- (void) showBack
{
    self.func(5,6);
}
- (void)dealloc
{
    self.func = nil;
    self.button = nil;
    [super dealloc];
}


IOS中的block相当于是一个在堆上的代码内存块,是需要释放的


2.C++的纳姆大表达式相当于block的实现

A视图:

void MyView::pageSwitch()
{
	SecondView* spSecondView = new SecondView;
	spSecondView->func = [](int x, int y)
	{
		return x + y;
	};
	spSecondView->func(10, 20);
}

B视图:(一定要用functional去包装)
#ifndef __testBlockCPlusPlus__SecondView__
#define __testBlockCPlusPlus__SecondView__


#include <functional>

class SecondView
{
public:
   SecondView(){};
   virtual ~SecondView(){};
   std::function<int(int, int)> func;
	
private:
   int originX;
   int originY;
};

c++中纳姆大表达式最坑爹的地方,栈对象的地址问题:

#include <iostream>
#include <functional>
void foo()
{
	int a = 1;
	int b = 2;
	int c = 3;
	
	f = [&]() {
		cout << a << endl;
		cout << b << endl;
		cout << c << endl;
	};
}

void bar()
{
	int x = 10;
	int y = 20;
	int z = 30;
	
	f();
	
	x = y = z = 0;
}

int main()
{
	foo();
	bar();
	
	return 0;
}


你可能感兴趣的:(IOS中的Block在C++中的运用)