I would like to replicate something like the built-in UIView
class method +animateWithDuration:animations:completion:
. So basically I am trying to write a method with a block where I can access/manipulate the inner variables.
Something like this:
int dur = 0.5;
[MyClass changeWithDuration:dur manipulations:^{
// I want to access these values and change them to the following values
// in 'dur' seconds, just like the built-in UIView class function does
myVariable = 0.5;
myOtherVariable = 1;
}];
I would like to use this in a Cocoa
application, so using the UIView
class method is out of the question.
If you want to access and modify variable you should add __block keyword:
__block int dur = 0.5;
[MyClass changeWithDuration:dur manipulations:^{
// I want to access these values and change them to the following values
// in 'dur' seconds, just like the built-in UIView class function does
myVariable = 0.5;
myOtherVariable = 1;
//Now you can change value go due variable
dur = 2.5;
}];
If there is a object you want to access, sometimes you need to create weak reference to that object to avoid retain cycles.
//Extended
If you want to do something similar to UIView animation blocks declare method in .h file:
// This just save typings, you don't have to type every time 'void (^)()', now you have to just type MyBlock
typedef void (^MyBlock)();
@interface MyClass : UIView
-(void)changeWithDuration:(float)dur manipulations:(MyBlock)block;
@end
And in your .m file:
-(void)changeWithDuration:(float)dur manipulations:(MyBlock)block
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:dur];
[UIView setAnimationDelay:0.0];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
if (block)
block();
[UIView commitAnimations];
}
To call the method you can do:
vi = [[MyView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
[vi setBackgroundColor:[UIColor redColor]];
[self.view addSubview:vi];
[vi changeWithDuration:3 manipulations:^{
vi.frame = CGRectMake(250, 20, 50, 40);
}];
Is it something you are after?
Okay, it does not seem to be possible...
iOS - Getting a variable from inside a block passed as a parameter
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.