Performing selector from within an Objective C block - iphone

I have been trying to use objective c blocks for the first time because I have really enjoyed using closures in languages such as Python and Haskell.
I have run into a problem however that I am hoping someone might be able to help with.
Below is a simplest version of the problem I am having.
typedef void(^BlockType)(NSString *string);
- (void)testWithtarget:(id)target action:(SEL)action
{
BlockType block = ^(NSString *string) {
[target performSelector:action withObject:data];
};
block(#"Test String"); // Succeeds
[self performSelector:#selector(doBlock:) withObject:block afterDelay:5.0f];
}
- (void)doBlock:(BlockType)block
{
block(#"Test String 2"); // Causes EXC_BAD_ACCESS crash
}
So it appears to be some sort of memory management issue which doesn't suprise me but I just don't have the knowledge to see the solution. Possibly what I am trying may not even be possible.
Interested to see what other people think :)

The block is not retained, since it is only present on the stack. You need to copy it if you want to use it outside the scope of the current stack (i.e. because you're using afterDelay:).
- (void)testWithtarget:(id)target action:(SEL)action
{
BlockType block = ^(NSString *string) {
[target performSelector:action withObject:data];
};
block(#"Test String"); // Succeeds
[self performSelector:#selector(doBlock:) withObject:[block copy] afterDelay:5.0f];
}
- (void)doBlock:(BlockType)block
{
block(#"Test String 2");
[block release];
}
It's a bit hap-hazard however since you're copying and releasing across method calls, but this is how you'd need to do it in this specific case.

Related

Objective-C passing a block into a block

This is a bit of a tricky scenario. I've been studying blocks and started implementing them for the first time, and I found myself wanting to create a "compound block". Here's my code, roughly:
- (void)moveToPosition:(NSInteger)pos withVelocity:(CGFloat)vel onCompletion:(void(^)(BOOL completed))completionBlock
{
void (^compoundBlock) (BOOL completed) = ^(BOOL completed) {
[self unlockInteractionFromPullDownMenuTab];
void(^innerCompletionBlock)(BOOL completed) = completionBlock;
innerCompletionBlock(completed);
};
// Animate
[UIView animateWithDuration: duration
animations: ^void{ [self.pullDownMenu setFrame:newFrame]; }
completion: compoundBlock
];
}
The goal is to take a block of code that is passed into this method, add something to it, and then pass it into an animation method call. However, I get a bad access on the line:
innerCompletionBlock(completed);
I figure that my innerCompletionBlock is getting deallocated, but I'm not entirely sure why. From what I understand, blocks copy everything that you throw at them, including references to self--which can create retain cycles, and which I recently learned to avoid.
Actually, I originally tried this:
void (^compoundBlock) (BOOL completed) = ^(BOOL completed) {
[self unlockInteractionFromPullDownMenuTab];
completionBlock(completed);
};
But I was getting the bad access, and I figured that perhaps the compoundBlock wasn't copying the completionBlock, so I explicitly declared a (block) variable inside the block and assigned it to try to get it to retain (perhaps a bit silly, but I'm running under ARC so I can't do manual retain calls).
Anyway, clearly the compoundBlock is being retained when it's passed to UIView, but I'm unsure how to retain my onCompletion/innerCompletionBlock within the compoundBlock since I'm running under ARC.
Thanks in advance :)
Aha, figured it out. Bit stupid, really.
There are various times where I was calling the method - (void)moveToPosition:... and passing nil to the completionBlock parameter...because I just didn't need to do anything extra at the end of the animation and only wanted the [self unlockInteractionFromPullDownMenuTab]; that was tacked on in the compoundBlock.
Makes sense, right?
...Only if you check for nil before you call the block. As discussed elsewhere on SO, "When you execute a block, it's important to test first if the block is nil". Well, I learned my lesson there.
This code works:
// Compound completion block
void (^compoundBlock) (BOOL completed) = ^(BOOL completed) {
[self unlockInteractionFromPullDownMenuTab];
if (completionBlock != nil) {
completionBlock(completed);
}
};
Blocks are created on the stack. You need to copy completionBlock to the heap so you can be sure it will still be valid when you try to run it. Just put this at the top of your method:
completionBlock = [completionBlock copy];
Note that if completionBlock is already on the heap, this just returns the same heap copy.

Creating the loop using GCD

So here is what I've got:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1*NSEC_PER_SEC), dispatch_get_current_queue(), ^{
bool ready = some_function();
if( ready ) {
do_smth_here()
} else {
//invoke this block one more time after 0.1 sec
}
});
The problem is how can I get the reference to the current block?
Instead of jumping through the hoops shown above, I typically declare an instance method that I can call that, internally, takes care of the retriggers as necessary. That way, any given block is one-shot, but the re-trigger creates a new block.
As long as the block creation isn't terribly expensive -- which it won't be if the state is coming from whatever encapsulates the instance method -- it is efficient enough and a heck of a lot simpler.
- (void) retriggerMethod
{
... do stuff here, assuming you want to do it on first invocation ...
dispatch_after( ..., ^{
[self retriggerMethod];
});
}
You can restructure it as needed. And you can easily add a BOOL instance variable if you want to protect against simultaneous retriggers, etc...
This also provides a convenient hook for canceling; just add a BOOL to the instance that indicates whether the next invocation should really do anything and re-schedule.
Jeffrey Thomas's answer is close, but under ARC, it leaks the block, and without ARC, it crashes.
Without ARC, a __block variable doesn't retain what it references. Blocks are created on the stack. So the callback variable points to a block on the stack. When you pass callback to dispatch_after the first time (outside of the block), dispatch_after successfully makes a copy of the block on the heap. But when that copy is invoked, and passes callback to dispatch_after again, callback is a dangling pointer (to the now-destroyed block on the stack), and dispatch_after will (usually) crash.
With ARC, a __block variable of block type (like callback) automatically copies the block to the heap. So you don't get the crash. But with ARC, a __block variable retains the object (or block) it references. This results in a retain cycle: the block references itself. Xcode will show you a warning on the recursive dispatch_after call: “Capturing 'callback' strongly in this block is likely to lead to a retain cycle”.
To fix these problems, you can copy the block explicitly (to move it from the stack to the heap under MRC) and set callback to nil (under ARC) or release it (under MRC) to prevent leaking it:
__block void (^callback)() = [^{
if(stop_) {
NSLog(#"all done");
#if __has_feature(objc_arc)
callback = nil; // break retain cycle
#else
[callback release];
#endif
} else {
NSLog(#"still going");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1*NSEC_PER_SEC), dispatch_get_current_queue(), callback);
}
} copy];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1*NSEC_PER_SEC), dispatch_get_current_queue(), callback);
Obviously you can drop the #if and just use the branch appropriate for your memory management.
I think this is the code your looking for:
__block void (^callback)();
callback = ^{
bool ready = some_function();
if( ready ) {
do_smth_here()
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1*NSEC_PER_SEC), dispatch_get_current_queue(), callback);
}
};
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1*NSEC_PER_SEC), dispatch_get_current_queue(), callback);
Thanks to ^ Blocks Tips & Tricks

create a method with return using a delay

working on xcode I realized that if I create a non-void method, I call it from a class / method, the result is processed optimally only if the action is immediate. I tried to do a test by inserting a delay and I realized that it no longer works.
I will write down here the example that I created:
Class A
//--------------------CLASS A
- (void)viewDidLoad {
[super viewDidLoad];
i = 0;
Class *classB = [[Class alloc] init];
i = [classB method1];
[self performSelector:#selector(method3) withObject:NULL afterDelay:1.8];
}
-(void)method3 {
NSLog(#"i = %i",i); // i = 0
}
Class B
//--------------------CLASS B
-(int)method1 {
[self performSelector:#selector(method2) withObject:NULL afterDelay:1];
return a;
}
-(void)method2 {
a = 800;
}
Obviously my problem is not something so trivial but I tried to make it easy to get an answer as thoroughly as possible, I was advised to use modal methods but I don't think that's the solution I was looking for.
What could I do to solve this?!
What you really need is a better understanding of asynchronous methods. In your method1, the variable a is never altered -- all you are doing is scheduling method2 to be called in the future and then returning the current state of variable a.
In Objective-C, there are a few different ways you can solve this problem. People most commonly use protocols and delegates to solve this issue. Here is a basic intro to protocols and delegates. Basically, you would want your class A object to be a delegate of your class B object. You could also use NSNotifications or blocks, although you should probably understand the usage of protocols and delegates (they are very important in Objective-C) before moving on to notifications and blocks.
What could I do to solve this?!
Where do you want to return the value to? In your example, method1 will complete long before method2 is ever invoked. If you want to preserve the value calculated by method2, you'll typically have that method store the value in one of ClassB's instance variables and possibly call some other method to continue processing.
If you really need method1 to return the result from method2, you'll need to call it synchronously (i.e. without -performSelector:withObject:afterDelay:). In this case, consider a) why you need the delay at all; and b) if you should perhaps be calling method1 after a delay instead of method2.
We'll be able to provide much better help if you can explain what the real-world problem that you're trying to solve is.

Calling a method in Objective-C that references another class file

I am trying to call a method that checks whether the player is bigger or smaller than the enemy. (this is a fish game)
In EnemyFish.m I am using this method
-(void) compareSize:(Player*)player{
if (self.fSize > player.pSize){
isBigger = true;
}
else{
isBigger = false;
}
}
Then I want to call this method during the update so I am doing this:
-(void) update {
[self compareSize];
//Check to see if bigger than player fish
if( isBigger == true){
//code for if bigger
}else{ //etc. }
I am getting an exception: sharedlibrary apply-load-rules all
not sure what the best way to set up this method would be, and the best way to call it, since [self compareSize] is definately not working.
Any help would be greatly appreciated, Thanks!
------UPDATE----------
What about if I use this
update:(Player *)player{
The problem I was running into here, is how to call this correctly, I wasn't sure how to change this to correctly call the new update method:
[self schedule:#selector(update) interval:1.0f/60.0f];
It is unclear what you are asking, but let's look at your code and see if it helps.
Your first method can be written more concisely as:
- (void) compareSize:(Player *)player
{
isBigger = self.fSize > player.pSize;
}
There is no point in using an if/else to assign a true/false (or YES/NO) value.
Looking at this method raises the obvious question of whether it would be better returning a value rather than assigning to an instance variable. This would look like:
- (BOOL) compareSize:(Player *)player
{
return self.fSize > player.pSize;
}
and now you can use a call to compareSize in an if.
Assuming the second version of compareSize your second method is:
-(void) update
{
//Check to see if bigger than player fish
if ([self compareSize]) // OOPS, no Player
{
//code for if bigger
}
else
{
//etc.
}
}
But this doesn't work as you need an instance of Player to pass to compareSize:, e.g. [self compareSize:somePlayerInstance]. So you now have to ask yourself where you expect the Player to be found; it could be an argument to update (e.g. - (void) update:(Player *)somePlayerInstance), or you might have a method to call which returns a whole collection of players and you need to test against each one, etc., etc. I can't give an answer as I've no idea of your game and algorithm!
Following comment
You must store a reference to your Player object somewhere in your application. If there is only a single player is Player designed as a singleton with a sharedInstance, or similarly named, class method that returns the single instance? If so then your update will contain:
if ([self compareSize:[Player sharedInstance]])
etc.
Another design pattern is to have your application delegate store the reference and to provide a method (or property) for accessing it. Following this pattern (and making up a class MyDelegateApp and property player names) your code might look like:
if ([self compareSize:((MyAppDelegate *)[NSApp delegate]).player])
Yet another model is to create the single player in the application's main XIB/NIB file - etc., etc., there are many application models!
You "simply" (its not simple of course) need to design your application model so that your single player is accessible, one way or another, where you need it...
Your compareSize: method (note the colon) requires a player parameter.
So you need to call it like this:
[someEnemyFish compareSize:somePlayer]
If self is the instance of EnemyFish you want, you can do [self compareSize:somePlayer], but your title seems to indicate self isn't an EnemyFish?

iPhone block scope confusion about accessing object references

Most of the documented examples of block usage demonstrate closure with simple variables, but I've been confounded by any attempts to access objects which are present in the surrounding code. For example, this crashes in an ugly, unhelpful way:
#interface VisualizerPreset : EyeCandyPreset {
float changeSourceRate;
float (^frontPanelSlider2DisplayValueBlock)(void);
}
....
VisualizerPreset *it;
it = [[VisualizerPreset alloc] init];
it.changeSourceRate = 0.4;
it.frontPanelSlider2DisplayValueBlock = ^(void) {
return it.changeSourceRate;
};
....
// this crashes
NSLog(#"%f",it.frontPanelSlider2DisplayValueBlock());
One possible reason is that you've lost the block. A block is created in stack, not in the heap. So if you want to keep the block, you have to copy it; this will make a copy of the block in the heap.
float (^aVar) = [^{return 0.0;} copy];
Of course, you will have to also release it later.
Be careful who owns the copy of the block. Inside a block, all referenced objects are automatically retained. So it is easy to create a reference cycle. You can use __block modifier for this problem. Consider reading this http://thirdcog.eu/pwcblocks/