Objective-C blocks syntax

Source: Internet
Author: User

The blocks in OC is similar to the function pointer in C ++. It can be seen from the appearance and usage.

INT (* cfunc) (int A); // function pointer in C language. Call intret = (cfunc) (10 );

INT (^ bfunc) (int A); // Blocks
Call intret = (bfunc) (10 );

You can also use the typedef keyword to define blocks.

Typedef (void) (^ bfunc) (int A, int B );

Bfunc func = ^ (int A, int B ){

Return A + B;

};

Func (); block can be called.

_ Blocks keywords

The following code:

typedef (void)(^BFunc)(int a,int b);__blocks int sum;BFunc func=^(int a,int b){sum=a+b;        return sum;};

If the _ blocks keyword is not used to modify sum, sum in the blocks block will prompt an error, which is not defined

Apple officially recommends that you use blocks as much as possible. This mechanism is widely used in multithreading, asynchronous tasks, and animation transfer. It can be used in callback.

Consider the following scenarios:

A person class and a dog class. Each person has a dog. When a dog sends a message, the owner is notified, that is, the method of the owner is called. This can be achieved through the Protocol. Here we use the blocks callback mechanism:

Person class

#import <Cocoa/Cocoa.h>#import "Dog.h"@interface Person : NSObject {Dog *_dog;}@property (retain)Dog *dog;@end
#import "Person.h"@implementation Person@synthesize dog=_dog;-(void)setDog:(Dog*)thisDog{if(_dog!=thisDog){[_dog release];_dog =[thisDog retain];[_dog setBarkCallback:^(Dog* thisDog,int count){NSLog(@"dog bark infom person ,id %d,count %d",[thisDog ID],count);}];}}-(Dog*)dog{return _dog;}-(void)dealloc{_dog=nil;[super dealloc];}@end

Dog

# Import <Cocoa/cocoa. h> @ interface dog: nsobject {int _ id; nstimer * timer; int barkcount; // defines a blocks Variable Void (^ barkcallback) (dog * thisdog, int count );} @ property (assign) int ID;-(void) setbarkcallback :( void (^) (dog * thisdog, int count) eachbark; @ end

# Import "dog. H "@ implementation dog @ synthesize id = _ id;-(void) updatetimer :( ID) Arg {nslog (@" Dog % d bark count % d ", _ id, ++ barkcount); // use blcok to report to person if (barkcallback) barkcallback (self, barkcount);}-(void) setbarkcallback :( void (^) (DOG * thisdog, int barkcount) eachbark {[barkcallback release]; barkcallback = [eachbark copy];}-(ID) Init {If (Self = [Super init]) {timer = [nstimer scheduledtimerwithtimeinterval: 1.0f target: Self selector: @ selector (updatetimer :) userinfo: Nil repeats: Yes];} return self ;}- (void) dealloc {[barkcallback release]; [Super dealloc] ;}@ end

Main Function

#import <Foundation/Foundation.h>#import "Person.h"#import "Dog.h"int main (int argc, const char * argv[]) {    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];    // insert code here...    NSLog(@"Hello, World!");Person *xiaoli=[[Person alloc]init];Dog *dog1=[[Dog alloc]init];[dog1 setID:10];[xiaoli setDog:dog1];[dog1 release];while (1) {[[NSRunLoop currentRunLoop]run];}    [pool drain];    return 0;}

The running result is as follows:

Beginner .. For more information, see.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.