objective c block

60
Block Khoa Pham - 2359Media

Upload: khoa-pham

Post on 17-Jul-2015

88 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Objective C Block

BlockKhoa Pham - 2359Media

Page 2: Objective C Block

BlockDefinitionSyntaxCaptureUsage

Page 3: Objective C Block

Definition

Page 4: Objective C Block

BlockThe closure that Apple adds to CIs an object (NSBlock)The compiler translate block literals into struct and functions. So we don’t see the alloc call

Page 5: Objective C Block

BlockIt is said to be the only object that can be allocated on the stack, by default.

It is moved to heap when copied.

Page 6: Objective C Block

Blockstruct + captured state information

Page 7: Objective C Block

Syntax

Page 8: Objective C Block

SyntaxThe syntax of Objective C block http://arigrant.com/blog/2014/1/18/the-syntax-of-objective-c-blocks

From C declarators to Objective C block syntaxhttp://nilsou.com/blog/2013/08/21/objective-c-blocks-syntax/

Cheatsheethttp://fuckingblocksyntax.com/

Page 9: Objective C Block

Syntax*[]()^

Page 10: Objective C Block

Syntax() > [] > *, ^Start from the variable name to rightThen to the leftOperator precedence http://unixwiz.net/techtips/reading-cdecl.html

CDECL http://cdecl.org/

Page 11: Objective C Block

Syntaxint a;

Page 12: Objective C Block

Syntaxint a;

a is an int

Page 13: Objective C Block

Syntaxint *a;

Page 14: Objective C Block

Syntaxint *a;

a is a pointer to an int

Page 15: Objective C Block

Syntaxint a[];

Page 16: Objective C Block

Syntaxint a[];

a is an array of int

Page 17: Objective C Block

Syntaxint f();

Page 18: Objective C Block

Syntaxint f();

f is a function that returns an int

Page 19: Objective C Block

Syntaxint f(long);

f is a function that returns an int, and accepts a long

Page 20: Objective C Block

Syntaxint *a[];

Page 21: Objective C Block

Syntaxint *a[];

a is an array of pointers to int

Page 22: Objective C Block

Syntaxint *(a[]);

a is an array of pointers to int

Page 23: Objective C Block

Syntaxint (*)a[];

Page 24: Objective C Block

Syntaxint (*)a[];

a is a pointer to an array of ints

Page 25: Objective C Block

Syntaxint *f();

Page 26: Objective C Block

Syntaxint *f();

f is function that returns a pointer to an int

Page 27: Objective C Block

Syntaxint *(f());

f is function that returns a pointer to an int

Page 28: Objective C Block

Syntaxint (*f)();

Page 29: Objective C Block

Syntaxint (*f)();

f is a pointer to a function which accepts nothing and returns an int

Page 30: Objective C Block

Syntaxvoid (^successBlock)(NSDictionary *response);

successBlock is a block pointer to a function which takes a dictionary and returns nothing

Page 31: Objective C Block

Syntax^ is the block pointer, which can only be applied to function

int ^f(); // Error

Page 32: Objective C Block

^ unary operatorint (^doubleMe)(int) = ^(int a){

return a * 2;}

int b = doubleMe(2);

Page 33: Objective C Block

^ unary operatorTransform function implementation into a blockInfer the return type

Page 34: Objective C Block

^ unary operatorBOOL (^customBlock)(NSArray *) = ^(NSArray *array) {

// return array.count == 3; // Please don’t

if (array.count == 3) {

return YES;

}

return NO;

};

Page 35: Objective C Block

__blockWhat does the block keyword meanhttp://stackoverflow.com/questions/7080927/what-does-the-block-keyword-mean

Page 36: Objective C Block

__blockAccess to __block variablehttp://clang.llvm.org/docs/Block-ABI-Apple.html#layout-of-block-marked-variables

By default, variables used withtin the block are copied Rewrite access,

Page 37: Objective C Block

__block (Kiwi example)describe(@"it takes a while", ^{

__block NSDictionary *apiResponse = nil;

beforeAll(^{

__block BOOL requestCompleted = NO;

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request

success:̂ (NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

requestCompleted = YES;

apiResponse = JSON;

}

failure:̂ (NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

requestCompleted = YES;

}

];

[operation start];

[KWSpec waitWithTimeout:3.0 forCondition:̂ BOOL() {

return requestCompleted;

}];

});

it(@"includes the related objects in the response", ^{

[[[apiResponse objectForKey:@"children"] should] containObjects:@"foo", @"bar", @"baz", nil];

});

});

Page 38: Objective C Block

Capture

Page 39: Objective C Block

CaptureThe ability to capture values from the enclosing scope, making them similar to closures or lambdas in other programming languages.

Page 40: Objective C Block

weakSelf vs strongSelf__weak __typeof__(self) weakSelf = self;

self.block = ^{

__typeof__(self) strongSelf = weakSelf;

[strongSelf doSomething];

[strongSelf doSomethingElse];

};

The block property is declared as “copy”

Page 41: Objective C Block

weakSelf vs strongSelfUnderstand weakSelf and strongSelfhttp://www.fantageek.com/1090/understanding-weak-self-and-strong-self/

Page 42: Objective C Block

weakSelf vs strongSelfBlock is allocated on the stack. It has no effect on the storage of lifetime of anything it accesses.

When they are copied, they take their captured scope with them, retaining any objects they refer

Page 43: Objective C Block

weakSelf vs strongSelfBlock captures the variable along with its decorators (i.e. weak qualifier),

Page 44: Objective C Block

weakSelf vs strongSelfBlock captures the variable along with its decorators (i.e. weak qualifier),

Page 45: Objective C Block

weakSelf vs strongSelfYou should only use a weak reference to self, if self will hold on to a reference of the block.

Page 46: Objective C Block

Take care

Page 47: Objective C Block

UIView animation block[UIView animateWithDuration:0.5 delay:1.0 options: UIViewAnimationCurveEaseOut animations:^{ self.basketTop.frame = basketTopFrame; self.basketBottom.frame = basketBottomFrame; } completion:^(BOOL finished){ NSLog(@"Done!"); }];

Page 48: Objective C Block

UIView animation block- (void)loopThisBlock { [UIView animateWithDuration:0.2 animations:^{ someView.alpha = (someView.alpha + 1.0) % 2; } completion:^(BOOL finished) { [self loopThisBlock]; }]; }

What if the block is executed infinitely ?

Page 49: Objective C Block

AFNetworking callback blockAFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager

manager];

[manager GET:@"http://example.com/resources.json" parameters:nil success:^

(AFHTTPRequestOperation *operation, id responseObject) {

NSLog(@"JSON: %@", responseObject);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"Error: %@", error);

}];

Page 50: Objective C Block

Notification handler block[[NSNotificationCenter defaultCenter]

addObserverForNotificationName:@"NotificationName"

object:nil

queue:[NSOperationQueue mainQueue]

block:^(NSNotification *notification) {

//reload the table to show the new whiz bangs

NSAssert(notification, @"Notification must not be nil");

[self.tableView reloadData];

}];

Page 51: Objective C Block

Usage

Page 52: Objective C Block

DSLMasonryKiwiFTGValidator

Page 53: Objective C Block

DSLREQUIRE_STRING(@"90001").to.matchRegExWithPattern(@"^[0-9][0-9][0-9][0-9][0-

9]$").with.message(@"Value must be US zip code format"),

[view1 mas_makeConstraints:^(MASConstraintMaker *make) {

make.edges.equalTo(superview).with.insets(padding);

}];

Page 54: Objective C Block

DSL- (FTGStringRule * (^)(NSString *anotherValue))equalTo { return ^(NSString *anotherValue){ [self setValidation:^BOOL(NSString *value) { return [value isEqualToString:anotherValue]; }]; return self; };}

Page 55: Objective C Block

Syntactic sugarhttps://github.com/supermarin/ObjectiveSugar

[@3 times:^{

NSLog(@"Hello!");

}];

[cars each:^(id object) {

NSLog(@"Car: %@", object);

}];

Page 56: Objective C Block

Syntactic sugarhttps://github.com/supermarin/ObjectiveSugar

[@3 times:^{

NSLog(@"Hello!");

}];

[cars each:^(id object) {

NSLog(@"Car: %@", object);

}];

Page 57: Objective C Block

Conditionhttp://blog.vikingosegundo.de/2012/10/05/pattern-switch-value-object/

NSArray *filter = @[caseYES, caseNO];id obj1 = @"YES";id obj2 = @"NO";[obj1 processByPerformingFilterBlocks:filter];[obj2 processByPerformingFilterBlocks:filter];

Page 58: Objective C Block

Mapping with blockhttp://www.merowing.info/2014/03/refactoring-tricks/#.VNw2IlOUc8Y

NSString *(^const format)(NSUInteger, NSString *, NSString *) = ^(NSUInteger value, NSString

*singular, NSString *plural) {

return [NSString stringWithFormat:@"%d %@", value, (value == 1 ? singular : plural)];

};

Page 59: Objective C Block

Reference1. http://www.galloway.me.uk/2012/10/a-look-inside-blocks-episode-1/2. https://blackpixel.com/writing/2014/03/capturing-myself.html3. http://albertodebortoli.github.io/blog/2013/04/21/objective-c-blocks-

under-the-hood/4. http://stackoverflow.com/questions/20134616/how-are-nsblock-objects-

created5. http://nilsou.com/blog/2013/08/21/objective-c-blocks-syntax/6. http://clang.llvm.org/docs/Block-ABI-Apple.html#blocks-as-objects7. http://albertodebortoli.github.io/blog/2013/08/03/objective-c-blocks-

caveat/

Page 60: Objective C Block

Thanks