简体   繁体   中英

Objective-C the ^ operator

I'm a newbie in Objective C and trying to figure out what does the ^ operator? While exploring some source code i saw next construction:

dispatch_once(&onceToken, ^{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(20.f, 13.f), NO, 0.0f);

    [[UIColor blackColor] setFill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 20, 1)] fill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 5, 20, 1)] fill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 10, 20, 1)] fill];

    [[UIColor whiteColor] setFill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 1, 20, 2)] fill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 6,  20, 2)] fill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 11, 20, 2)] fill];   

    defaultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

});

And I'd like to know what is the ^?

The ^ indicated the start of a block definition within Objective-C.

Have a look in here: http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxGettingStarted.html#//apple_ref/doc/uid/TP40007502-CH7-SW1

Note that in this context, the ^ is not an operator, it is part of the syntax of Objective-C @Mike's down-voted answer is strictly the correct definition of the "^ operator"

It is called a Block In Objective C

Syntax:

returnType (^variableName)(parameters);

Taken verbatim from a tutorial by Akiel Khan , (you can find another good tutorial here ) :

  • The block literal is “anonymous” (ie nameless)
  • The caret (^) symbol
  • We didn't have to specify the return type – the compiler can “infer” it. We could've explicitly mentioned it if we wanted to.

This is a Official Documentation, read it for more information.

Here it is a signal for beginning a block.

You can find more information of block by reading some tutorial blogs or articles:

Blocks – An Interesting Objective-C Addition In iOS 4

How To Use Blocks in iOS 5 Tutorial

When you know the basic thing of block, you can refer to Apple's document about block .

In fact, the most regular use of block will be GCD (stands for Grand Central Dispatch, which is your case in question), UIView's animation and something other like a callback. It is very useful and common in modern Obj-C programming.

It is used to create blocks in object c blocks are just like function pointers in c. This may help you

checkout this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM