Upgrade to PRO for Only $50/Year—Limited-Time Offer! 🔥

iOS app Development - Block

iOS app Development - Block

高見龍

April 15, 2014
Tweet

More Decks by 高見龍

Other Decks in Programming

Transcript

  1. no return type and params void (^myBlock)(void) = ^(void) {

    NSLog(@"Hello, Block"); }; myBlock();
  2. no return type and params (cont.) void (^myBlock)() = ^{

    NSLog(@"Hello, Block"); }; myBlock();
  3. get variable out of the block int mutiplier = 10;

    int (^myAdd)(int, int) = ^(int a1, int a2) { return (a1 + a2) * mutiplier; };
  4. define type for block typedef int (^MyBlockType) (int, int); MyBlockType

    myAddType = ^(int a1, int a2) { return a1 + a2; };
  5. return value to block typedef void (^CompleteBlock) (NSString* title, NSString*

    author); typedef void (^FailBlock) (NSError* error); @interface DemoClass : NSObject - (void) fetchBookWithID:(NSInteger) bookID complete:(CompleteBlock) complete fail:(FailBlock) fail; @end @implementation DemoClass - (void) fetchBookWithID:(NSInteger)bookID complete:(CompleteBlock)complete fail:(FailBlock)fail { if (/.. something error.. /) { fail(error); } else { complete(@"This is a book", @"eddie kao"); } } @end
  6. return value to block (cont.) DemoClass* demo = [[DemoClass alloc]

    init]; [demo fetchBookWithID:10 complete:^(NSString *title, NSString *author) { NSLog(@"book title = %@, and author = %@", title, author); } fail:^(NSError *error) { NSLog(@"error = %@", error); }];
  7. for-in v.s block enumeration NSArray* array = @[@1, @2, @3,

    @4, @5]; for (id obj in array) { NSLog(@"%@", obj); } [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"%@", obj); }];
  8. UIAnimation, the old way - (void)viewDidLoad { [super viewDidLoad]; UIView*

    myView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; myView.backgroundColor = [UIColor redColor]; [self.view addSubview:myView]; [UIView beginAnimations:@"Demo" context:nil]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(endAnimationHandler)]; [UIView setAnimationDuration:3]; myView.alpha = 0; [UIView commitAnimations]; } - (void) endAnimationHandler { NSLog(@"animation end!"); }
  9. UIAnimation, the block way - (void)viewDidLoad { [super viewDidLoad]; UIView*

    myView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; myView.backgroundColor = [UIColor redColor]; [self.view addSubview:myView]; [UIView animateWithDuration:3 animations:^{ myView.alpha = 0; } completion:^(BOOL finished) { NSLog(@“animation end!”); }]; }