Object-C中的块(Block)

时间 : 14-10-08 栏目 : iOS, 移动开发 作者 : noway 评论 : 0 点击 : 339 次

在Object-C中,块的概念和我们熟知的函数式编程中的块概念一致,就是一个独立的逻辑处理单元,据说苹果公司为C,C++和Object-C都扩充了支持块的语法。苹果的系统是在Mac OSX10.6,iOS4.0以后支持块的。 

在Object-C中,块被当做一个对象来处理,这个对象可以: 

  • 有自己的局部变量
  • 可以传入参数
  • 有返回值
  • 可以访问自己定义时的上下文变量
  • 可以修改自己定义时特定的上下文变量
  • 作为参数传递给其它函数



在引入块特性之后,iOS4.0以后,很多新的API都使用了块做为参数来作为某个操作完成之后的回调。下面就来看一个例子: 

Object-c代码  收藏代码
  1. - (Player *)playerAtPosition:(PlayerPosition)position {  
  2.     __block Player *player;  
  3.     [_players enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {  
  4.         player = obj;  
  5.         if (player.position == position)  
  6.             *stop = YES;  
  7.         else  
  8.             player = nil;  
  9.     }];  
  10.     return player;  
  11. }  


这段代码的功能是在一个Dictionary中找到指定位置的玩家。代码中调用了SDK中NSDictionary类的方法: 

Object-c代码  收藏代码
  1. - (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);  


该方法使用了一个块作为参数,表示遍历Dictionary中的每个对象时做的操作,以及什么时候停止遍历。 

在例子代码中,还可以看到一个块的结构,块的定义分4部分: 

  • 'void'表示返回值为空;
  • '(^)'表示接下来定义的是一个块;
  • '(id key, id obj, BOOL *stop)'表示该块接受三个参数,他们的类型分别为对象,对象和布尔类型;
  • '{…}'中的内容表示块的具体处理逻辑;


苹果官网上的图是这个样子的:

blocks

另外,代码中访问了方法的参数position,表示块可以访问自己定义时的上下文中的变量。 

除此之外,块的代码中对上下文中的变量player进行了修改,因此在定义player变量时使用了'__block'关键字,表示该变量可以在块中修改。如果不加该关键字,编译器会报错“Assignment of read-only variable 'player'”。这是因为代码块内使用的是变量的副本,它是堆栈里的一个常量。这些变量在代码块中是不可改变的。。 

其实,块从本质上来说是一个闭包,即其拥有代码逻辑和运行该段代码逻辑需要的变量。这一切在定义代码时就已经确定,因此,一个块在定义时访问了某个上文变量,即使之后该上下文变量发生了变化,块中仍然使用是定义时的值,可以认为块只是在定义的时候拷贝了一个变量值到自己的作用域。定义完之后,和原来的那个上下文变量就没有关系了。 

Object-c代码  收藏代码
  1. NSDate *date = [NSDate date];  
  2. void (^time)(void) = ^ {  
  3.     NSLog(@"The date and time is %@", date);  
  4. };  
  5. time();  
  6. NSLog(@"The date and time is %@", date);  
  7.   
  8. sleep(10);  
  9. date = [NSDate date];    
  10. NSLog(@"The date and time is %@", date);//返回5秒后的新时间  
  11. time();//仍然返回上一次的时间  

本文标签

除非注明,文章均为( noway )原创,转载请保留链接: http://blog.z3a105.com/?p=235

Object-C中的块(Block):等您坐沙发呢!

发表评论





       ==QQ:122320466==

 微信    QQ群

推广

  • 104726drf320ff09r7i62f.jpg
  • 103217vn3333zbk3snwz2u.jpg

0

Aujourd’hui, une partie avec le développement du e-commerce, achats en ligne est devenu une partie de la vie pour beaucoup de gens. La mariage a commencé achats en ligne. Si vous choisissez achats les mariages en ligne, il peut être beaucoup moins cher que le salon de la Robe de mariée pas chermariée local, réduisant le budget de mariage. vous pouvez avoir beaucoup de choix si acheter de mariage en ligne. vous pouvez ramasser une robe de mariée bon marché sur Internet.
Piercing fascinerande figur, och nu tittar vi på 2016 senast brudklänning, kan du vara den vackraste bruden det!2016 senaste Bra brudklänning, söt temperament Bra design, romantiska spetsar blomma kjol, som du lägger till en elegant och charmig temperament.Kvinnan tillbaka mjuka linjer, människor brudklänningofta få en känsla av oändlig frestelse. Fall 2016 mässan, lämnar uppgifter om ditt bröllop charmig.
Yesterday afternoon, the Chinese team was training in the Guangzhou Gymnasium, when the reporter asked Zhao Yunlei the feeling of wearing the new cheap jersey , cheap jerseys online shopshe readily took a shirt from the bag crumpled ball to reporters, and she said with a smile: ” This shirt is light. ”Zhao Yunlei said: “Our material is very light like with the clothes of the tennis King Nadal, Federer, after the sweat, sweat does not drip down to the ground, when we do move, it is easy pace slipping if the sweat drip on the floor.”Tennis players Zhang Yawen, told reporters: “You might think the clothes attached to the body, fearing we swing will be affected, in fact, we do not feel anything, because the clothes are very light, very soft, put on quite comfortable. And it’s particularly good clothes to dry, washing and will dry in 15 minutes. ”
China’s sports enthusiasts NFL sweatshirt with mad love and the pursuit of, and therefore, NFL jerseys have a good market in China and development. China is a populous country, is the consumer, the economic momentum is so good, the sales prospects sportswear is immeasurable. With hot sales sweatshirt, but also to promote the importance of sports fans, on health, on the other hand is a matter of concern for the World Cup, fans wearing NFL jerseys and also can express themselves more fully love and obsession Therefore, NFL jerseys Wholesale jerseys online shopwholesale has good prospects and development in China.
ANTA-ANTA Sports Products Limited, referred to as ANTA Sports, Anta, is China’s leading sporting goods companies, mainly engaged in the design, development, manufacture and marketing of ANTA brand sporting goods, including sports footwear, apparel and accessories. Anta sweatshirt design advantages, warm stretch knit fabric, using Slim version of model, more personal fit, bid farewell to bloated, so wearing more stylish.GUIRENNIAO-This logo is a spiritual totem, smooth graphics implication unstoppable force; flexible deliver an elegant arc Wholesale jerseys china shop movement, strength and speed of the United States, a symbol of passion and rationality publicity “Heart” and “meaning”, “concept” unity; pass the fearless and enterprising mind, showing beyond the realm of self, to unstoppable force to create the future.XTEP-Xtep (China) Co., Ltd. is a comprehensive development wholesale jerseys china shop, production and marketing of Xtep brand (XTEP) sports shoes, clothing, bags, caps, balls, socks mainly large sporting goods industry enterprises.
There are a lot of fans in identifying the authenticity of the above cheap jerseys have great distress, so here to i will show you some methods to definitely affordable inexpensive cheap jerseys : Firstly, we should look at if it is working fine. China has been called the world’s factory, a lot cheap jerseys factories in China have foundries, but our cheap jerseys are all from here! Secondly, should to see whether it is the , we all know that it is difficult to get out of print once a genuine cheap cheap jerseys free shipping jersey was print. and we have all kind of stocka on the whole website, in other words, we have all you want ! Finally, look at the price, our price is not necessarily the lowest in the whole website but it must be most fair on the whole website, we certainly you will not regret later when you buy it. Of course, except that cheap jerseys, we also have the other products, such as socks, leggings and some other related products, everyone can enjoy the best services of here!