Extract block parameter
With the Extract Block Parameter refactoring, you can create a block declaration based on the selected chunk of code within a method. As a result, the created block is passed as a parameter to this method, and all existing usages of this method are changed accordingly.
Extract a block parameter
In the editor, select a chuck of code (within a method) which you want to replace with a block declaration.
Select
from the main or context menu.In the dialog that opens, type the name of the block. If necessary, add/delete parameters, edit parameter names and types, and click Extract.
Code example
Before | After |
---|---|
- (void)performLogin {
// ...
[self.loginModel loginWithEmail:email password:password completion:^(BOOL success) {
// This code block will be extracted
if (success) {
[self showAlertLoginSuccess];
} else {
[self showAlertLoginFailed];
}
}];
}
- (IBAction)buttonLoginPressed:(id)sender {
// Method's call
[self performLogin];
}
|
- (void)performLogin:(void (^)(BOOL))completion {
// ...
[self.loginModel loginWithEmail:email password:password completion:^(BOOL success) {
// Extracted block
completion(success);
}];
}
- (IBAction)buttonLoginPressed:(id)sender {
// Method's call with the extracted block
// as a parameter
[self performLogin:^(BOOL controller) {
if (controller) {
[self showAlertLoginSuccess];
} else {
[self showAlertLoginFailed];
}
}];
}
|
Last modified: 08 March 2021