Search code examples
objective-cdelegatesprotocolsblockcodeblocks

Objective-C. Using blocks to reduce amount of code?


For example, I need to implement an object moving. It is left, right, up and down methods.

Edited

The following code is incorrect but I hope it will explain the thing I need better:

@interface A : NSObject
...
@end

@implementation A
-(void)up
{
  [self moveTo:^{/*block1*/}];
}

-(void)down
{
    [self moveTo:^{/*block2*/}];
}

-(void)left
{
  [self moveTo:^{/*block3*/}];
}

-(void)right
{
  [self moveTo:^{/*block4*/}];
}

-(void)moveTo:(CodeBlock *)b {
  //actions before
 ...
  b
  //actions after
 ...
}
@end

Solution

  • The solution

    For my example:

    -(void)left
    {
        [self moveTo:^(CGPoint p) {
            p.x--;
            return p;
        }];
    }
    
    -(void)moveTo:(CGPoint(^)(CGPoint))block
    {
        CGPoint p = sprite.position;
        p = block(p);
        sprite.position = p;
    }
    

    Right, up and down methods are similar to left method. So don't told me that it is incorrect question or that the solution is impossible