I am hooked into SpringBoard method, i want to wait a certain event to happen and then continue my code, but whatever i try - i think it pauses the main thread and all threads stop then. My code is:
+(void) startc {
while([currentNumber isEqual:#""])
{
NSLog(#"waiting until currentNumber is not empty %#", currentNumber);
}
}
id replaced_SBCallAlert_initWithCall_(id self, SEL _cmd, CTCallRef call) { // Note the
NSLog(#"calling replaced");
[cdBackground startc];
original_SBCallAlert_initWithCall_(sbc, scc, cls);
return NULL;
}
currentNumber is updated in another thread, but this code blocks it.
Your while loop in startc is effectively a spin lock, and will prevent any further progress on a thread executing it until currentNumber is not #"". If that same thread is the one responsible for changing currentNumber, then yes - you have a deadlock. It looks like this is the case, as I guess you're expecting the call original_SBCallAlert_initWithCall_ to change this variable but are getting stuck inside the previous line's startc call.
In this case, you'll have to change the way your program is designed. You could put startc in a background thread (look at NSThread) and use either another spin lock, NSCondition or key-value observing to "wake up" when currentNumber has changed. You can then use NSObject performSelectorOnMainThread … (assuming you have a runloop) to kick off your code again in the "main" thread, or carry on in your background thread.
Related
If I have the method defined below, does the block ("handler") passed to the method get called on the new thread created by NSOperationQueue? Or does it get called on the thread it was on when passed to methodWithCompletionHandler:?
-(void)methodWithCompletionHandler:(void (^)(NSString *message))handler
{
// Note: We are currently on thread #1. Calling handler(#"my message") here
// will run on thread #1.
NSBlockOperation* someOp = [NSBlockOperation blockOperationWithBlock: ^{
// do some stuff
}];
[someOp setCompletionBlock:^{
// Note: Now someOp is completing, but it's in thread #2. Does calling the handler
// as below also run in thread #2 or thread #1?
handler(#"Some message.");
}];
NSOperationQueue *queue = [NSOperationQueue new];
[queue addOperation:someOp];
}
From the documentation:
The exact execution context for your completion block is not
guaranteed but is typically a secondary thread.
http://developer.apple.com/library/ios/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html#//apple_ref/doc/uid/TP40004591-RH2-SW36
In the example you have posted, the block in someOp would be executed on a different thread.
In general, blocks act just like a regular function. They run on the thread that called them (unless the block itself does something to call another thread etc...)
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.
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
My problem is that I'm using dispatch_async(dispatch_get_main_queue(), ^(void) { ... }); to call a method asynchronously, in this method depending on some conditions i set a boolean to YES. When this boolean is read in this method, it's always read by it's old value which is NO.
The weird thing is that when i made a breakpoint on the line where the bool is checked, everything went fine and as intended !
EDIT:
Here is the code where the threads are spawned
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self drawFaceBoxesForFeatures:features forVideoBox:claporientation:curDeviceOrientation image:img];
});
The method itself
- (void)drawFaceBoxesForFeatures:(NSArray *)features forVideoBox:(CGRect)clap orientation: (UIDeviceOrientation)orientation image:(UIImage *)image;
{
if (![self getSendingRequestStatus]) {
NSLog(#"Sending req");
// send async request
dispatch_async(dispatch_get_main_queue(),^ {
sendingRequest = YES;
} );
}
}
It looks like you are modifying an ivar that was created outside of a block inside of the block. In order to do this and have the ivar hold the correct value, you are going to need to use the __block keyword like so:
#interface MyCoolClass : NSObject {
#private
__block int sendingRequest_;
}
As Jack Lawrence said in the commend above, "[the runtime] takes a snapshot of all of the relevant objects/variables at that point in time". The __block identifier will tell the runtime that it should not copy that ivar to the heap and will allow you to assign values to sendingRequest_ inside of a block, even if that block is simply being run on the main thread.
A lot of good information to start with (including the above) can be found in the Blocks Programming Guide.
When primitives are passed into a block they are copied. So if you put a primitive local or instance variable in a block and then later change it either in the same method that created the block (after the block creation) or another method it won't have any effect on the variable in the block. In the case of a local variable, just make sure you make any necessary changes before block creation. In the case of instance variables you could try accessing the instance variable by using some C: self->iVar or declare it as a property and access it through the property accessor: self.iVar.
When I call performSelectorInBackground several times, would the job be queued on same thread?
so first one be performed first and so on?
Or, would it run in separate thread?
Thank you
A new thread is created with each call to -performSelectorInBackground:withObject:
From http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html#//apple_ref/doc/uid/10000057i-CH15-SW13
Using NSObject to Spawn a Thread
In iOS and Mac OS X v10.5 and later, all objects have the ability to spawn a new thread and use it to execute one of their methods. The performSelectorInBackground:withObject: method creates a new detached thread and uses the specified method as the entry point for the new thread. For example, if you have some object (represented by the variable myObj) and that object has a method called doSomething that you want to run in a background thread, you could could use the following code to do that:
[myObj performSelectorInBackground:#selector(doSomething) withObject:nil];
The effect of calling this method is the same as if you called the detachNewThreadSelector:toTarget:withObject: method of NSThread with the current object, selector, and parameter object as parameters. The new thread is spawned immediately using the default configuration and begins running. Inside the selector, you must configure the thread just as you would any thread. For example, you would need to set up an autorelease pool (if you were not using garbage collection) and configure the thread’s run loop if you planned to use it. For information on how to configure new threads, see “Configuring Thread Attributes.”
They will be executed in the same time, NOT one after the other,
try this to have an idea:
-(void)prova1{
for (int i = 1; i<=10000; i++) {
NSLog(#"prova UNO:%i", i);
}
}
-(void)prova2{
for (int i = 1; i<=10000; i++) {
NSLog(#"_________prova DUE:%i", i);
}
}
SEL mioMetodo = NSSelectorFromString(#"prova1");
[self performSelectorInBackground:mioMetodo withObject:nil];
SEL mioMetodo2 = NSSelectorFromString(#"prova2");
[self performSelectorInBackground:mioMetodo2 withObject:nil];
you'll get:
...
___prova DUE:795
prova UNO:798
___prova DUE:796
prova UNO:799
___prova DUE:797
prova UNO:800
___prova DUE:798
prova UNO:801
___prova DUE:799
prova UNO:802
___prova DUE:800
prova UNO:803
___prova DUE:801
...
if you want a queue with 1 method after the other, try to add the 2 methods to a NSOperationQueue and set its setMaxConcurrentOperationCount to 1...