1

I was studying blocks and it seems pretty impressive to use. But then I came to know that we can use blocks in functions as variable and its main use is when we want to do some async work that after getting result of something we have to perform some action.

I looked into a lot of resources and got what they were doing. I tried to do the same just by passing string like this:

Defining a block as parameter in .h file

typedef void(^sudBlock)(NSString * myname);

- (void)blockAsLastParam:(NSString*)name completion:(sudBlock)blockName;

Implementing a block as parameter in .m file

-(void) blockAsLastParam:(NSString *)name completion:(sudBlock)blockName{
    blockName(name);
}


[self blockAsLastParam:@"sudh" completion:^(NSString *myname) {
        NSLog(@"This is block %@",myname);
    }];

So here I am passing "sudh" as a string and getting it again.

Still I am not sure how the while thing works. Is there a tutorial where how things are done is perfectly captured with drawings.

I have read a lot of articles but they only tell us the way it needs to be implemented but don,t tell why this implementation do this stuff. Also how does parameter transfer is going on in functions called .

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sudhanshu Gupta
  • 2,255
  • 3
  • 36
  • 74
  • What you want to achieve? Read this from [Apple doc](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html) – Omer Malik Aug 28 '16 at 11:16
  • I don't want to achieve anything just looking into its usage . If i could get a example how we call API and pass its results to the function. It would be good – Sudhanshu Gupta Aug 28 '16 at 11:19
  • This link can help you to understand what blocks are. http://rypress.com/tutorials/objective-c/blocks – Leena Aug 28 '16 at 14:46

1 Answers1

0

You can do something like this.

You can process your string in block and send the result back using myResultFunction, in myResultFunction you can do what ever you want, but if you want to update UI use dispatch_get_main_queue, as shown below in the example,

[self blockAsLastParam:@"sudh" completion:^(NSString *myname) {

     NSString *processedString = @"";

     //Do your processing here your own logic
     [self myResultFunction:processedString];

}];

-(void)myResultFunction:(NSString*)porcessedString{
          //do anything with your String

         //UpDate UI
         dispatch_async(dispatch_get_main_queue(), ^{
        //write logic here for updating UI like updating textfield or label
    });           

}
Omer Malik
  • 409
  • 7
  • 15