Reputation: 52093
I'd like to know what are the advantages or disadvantages of naming the parameter of the block you pass to methods?
- (void)someMethod:(NSString * (^)(NSString *parameterName))block
{
NSString *value = block(@"Hello World");
}
- (void)someMethod:(NSString * (^)(NSString *))block
{
NSString *value = block(@"Hello World");
}
Are there any benefits when you know the name of the parameter of the block?
PS: Both of them are working correctly and doing the same thing.
Upvotes: 0
Views: 213
Reputation: 130082
Naming the parameter is needed only when you are defining the block:
NSString * (^myBlock)(NSString *) = NSString * (^)(NSString *parameterName)) {
NSLog(@"Printing %@", parameterName);
};
obviously, if you want to use the parameter, then the parameter needs a name.
When you are only passing to the parameter (executing the block), parameter names are completely optional although some people could consider them a way to document the code.
However, using id
instead of NSString *
would be considered a bad style by most programmers. It's better to use the specific type because it will protect you from passing an unexpected object (e.g. NSNumber
).
Upvotes: 2
Reputation: 9835
Assuming you are expecting a certain object type inside that function, the major benefit is that when you call the block the compiler (and developer) knows what type the block is actually expecting.
Upvotes: 0
Reputation: 5698
3 main reasons,
1) Your compiler will help you ensure that you are placing the blocks in the correct place, by checking the type return
2) XCode will help you with intellisense, by giving you available methods you can use from your parameter (e.g [string characterAtIndex:1]
)
3) Readability, it will be easier for somebody else to understand what you are doing.
Performance will be the same either way, so that's why most of the time people will opt for strict typing
Upvotes: 1
Reputation: 750
The type 'id' turns off compiler checking for selectors and will not emit warnings if you call methods without definitions. It does not mean that you inherit from NSObject.
If you know the actual type your block is expecting, it is better to use the type. If you do, misuse of your block will appear as a compiler warning.
Also, if you include an actual name for your block parameter, autocomplete will include that name, which is helpful when writing code.
Upvotes: 0