Reputation: 11
hello everyone I am new to IOS developement and I am working of block functions.I am confused about their working.My question is can we print the block function's parameters to outside its block. My code is like
[messageRenderingOperation start:^(NSString * plainTextBodyString, NSError * error) {
NSLog(@"plain text:%@",plainTextBodyString);
}];
NSLog(@"plain text body:%@",plainTextBodyString);
My output ids as follows:-
plain text:hello world
plain text body:(null)
why this value is null. Please help me.
Upvotes: 0
Views: 100
Reputation: 335
declare one variable outside block
__block NSString *plainTextString;
[messageRenderingOperation start:^(NSString * plainTextBodyString, NSError * error) {
//assign value
plainTextString =plainTextBodyString;
NSLog(@"plain text:%@",plainTextBodyString);
}];
//now you can access variable
NSLog(@"plain text body:%@",plainTextString);
or,
__block NSString *plainTextString;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[messageRenderingOperation start:^(NSString * plainTextBodyString, NSError * error) {
//assign value
plainTextString =plainTextBodyString;
NSLog(@"plain text:%@",plainTextBodyString);
dispatch_semaphore_signal(semaphore); }];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//now you can access variable
NSLog(@"plain text body:%@",plainTextString);
Please refer this tutorial for more details https://developer.apple.com/library/mac/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html
Upvotes: 1