Inline Block in iOS
ios, objective-c-blocks
Solution
That probably means, that you can directly place the definition of a Block in place of an block argument:
Given an API with a Block as parameter:
- (void) doSomethingWithBlock:(void(^)(id param))block;
Note the block's type is
typedef void(^block_type)(id param);
that is, it has parameter param of type `id` and returns `void`.
Now, you can define a Block inline:
...
[self doSomethingWithBlock:^(id param) {
// implementation
});
as opposed to define a Block "out of line":
block_type myBlock = ^(id param) {
// implementation
};
and calling it via:
[self doSomethingWithBlock:myBlock];
Problem
Iam completely new to iOS blocks . I have read in a book about inline blocks in ios . what exactly is inline blocks ? can we use it with any object ? what is the difference between normal and inline blocks ? this is what i saw in the book Using an inline block instead of a callback function ``` NSArray* arr2 = [arr sortedArrayUsingComparator: ^(id obj1, id obj2) { NSString* s1 = obj1; NSString* s2 = obj2; NSString* string1end = [s1 substringFromIndex:[s1 length] - 1]; NSString* string2end = [s2 substringFromIndex:[s2 length] - 1]; return [string1end compare:string2end]; }]; ``` A block defined inline, as in above example , isn’t reusable; if we had two calls to sorted- ArrayUsingComparator: using the same callback, we’d have to write out the callback in full twice. To avoid such repetition, or simply for clarity, a block can be assigned to a variable, which is then passed as an argument to a method that expects a block, as in below example. Assigning a block to a variable ``` NSComparisonResult (^sortByLastCharacter)(id, id) = ^(id obj1, id obj2) { NSString* s1 = obj1; NSString* s2 = obj2; NSString* string1end = [s1 substringFromIndex:[s1 length] - 1]; NSString* string2end = [s2 substringFromIndex:[s2 length] - 1]; return [string1end compare:string2end]; }; ``` NSArray* arr2 = [arr sortedArrayUsingComparator: sortByLastCharacter]; NSArray* arr4 = [arr3 sortedArrayUsingComparator: sortByLastCharacter]; Perhaps the most remarkable feature of blocks is this: variables in scope at the point where a block is defined keep their value within the block at that moment, even though the block may be executed at some later moment. (Technically, we say that a block is a closure, and that variable values outside the block may be captured by the block.) This aspect of blocks makes them useful for specifying functionality to be executed at some later time, or even in some other thread.