Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ^?

like image 536
HackU Avatar asked Mar 25 '13 14:03

HackU


3 Answers

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"

like image 93
Petar Avatar answered Oct 28 '22 21:10

Petar


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” (i.e. 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.

like image 24
iPatel Avatar answered Oct 28 '22 21:10

iPatel


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.

like image 4
onevcat Avatar answered Oct 28 '22 19:10

onevcat