Retry Objective-C method until a condition is met - objective-c

I have a method which is called, and the first thing it does is ascertain when the network is reachable. If it's not, I'd like to wait 10s, then run the same method with the arguments/params that were initially passed in..
This is my disastrous attempt (I'm more a JS dev, relatively new to Objective-C):
- (void)sendRequestToURL:(NSString *)url withPostData:(NSString *)postData withPage:(int)page sortBy:(NSString *)sort completionBlock:(void (^)(NSDictionary *))completion {
if(![FooNetworkManager isReachable]){
self.lastRequest = ??? // lastRequest is an NSDictionary
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 10);
dispatch_after(delay, dispatch_get_main_queue(), ^(void){
[self sendRequestToURL:self.lastRequest]; // this is almost definitely wrong
});
}
}
In JavaScript, inside a method we have access to the arguments object that contains all the params that were passed into the method, not sure how to replicate this in Objective-C.
Also, self.lastRequest is defined further up in this same class:
#property(nonatomic, strong) NSDictionary *lastRequest;

In its simplest form you can dispense with lastRequest and do:
- (void)sendRequestToURL:(NSString *)url withPostData:(NSString *)postData withPage:(int)page sortBy:(NSString *)sort completionBlock:(void (^)(NSDictionary *))completion {
if(![FooNetworkManager isReachable]){
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 10);
dispatch_after(delay, dispatch_get_main_queue(), ^(void){
[self sendRequestToURL:url withPostData:postData withPage:page sortBy:sort completionBlock:completion];
});
}
}
in this way you're simply capturing the passed parameters in the block. So you need to be careful that capturing mutable objects, if you have any, is acceptable...
You should also have some way to cancel the retry, or perhaps a maximum number of attempts, or even an exponential back off time in between attempts.

Related

Delaying a method on a separate thread in objective C

Is there a way to delay a method call before it changes a key value in the user defaults?
For instance; I have method A which is an IBAction and Method B. If a key "keyOne" is false; method A sets "keyOne" to true via the -[NSUserDefaults setBool: forKey:] and then calls method B with an integer input of for time delay. Method B then needs to wait for whatever the delay was input to be in seconds and then change the "keyOne" back to true with the same NSUserDefaults.
Use GCD's dispatch_after() to delay the operation. But, instead of using the main queue as generated by the Xcode code snippet, create your own queue, or utilize the background queue.
dispatch_queue_t myQueue = dispatch_queue_create("com.my.cool.new.queue", DISPATCH_QUEUE_SERIAL);
double delayInSeconds = 10.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, myQueue, ^(void){
// Reset stuff here (this happens on a non-main thead)
dispatch_async(dispatch_get_main_queue(), ^{
// Make UI updates here. (UI updates must be done on the main thread)
});
});
You can find more information on the difference between using performSelector: and dispatch_after() in the answer in this post: What are the tradeoffs between performSelector:withObject:afterDelay: and dispatch_after
You can use perform selector from method A to call method B:
[self performSelector:#selector(methodName) withObject:nil afterDelay:1.0];
If your method B needs to know the delay you can use withObject: to pass parameter, it needs to be NSNumber, not integer.

Test a GCD block as the async process is taking some time

I am developing an app that contacts a RESTful server to get some data and then with the returned JSON response to display that data.
Using UniRest calls and all is working well. The main call is 'runUnirestRequest'
The uni rest call is an async GCD dispatch call. My problem is that because I am testing locally the call is so quick I can't see the activity indicator rolling. It simply disappears before I can see it.
The GCD block occur within the viewController viewDidLoad call.
What I need to achieve: Have the async unirest call take several seconds to simulate a server response that is slow (Dont want to actually stop the iOS app in its tracks).
Please excuse any coding errors/bad habits, only been doing objective c for a week but am happy for any additional constructive crit. :)
I have tried
sleep(5); // But bad idea as far as I can see.
Also tried
[NSThread sleepForTimeInterval:5.0]; // but this doesn't seem to do anything.
viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
[self createActivityIndicator];
NSLog(#"viewDidLoad");
NSLog(#"viewDidLoad->thread: %#", [NSThread currentThread]);
[messageLabel setText:#""];
unirestQueue = dispatch_queue_create("com.simpleweb.pbs.dayDataUnirestRequest", NULL);
// Do any additional setup after loading the view from its nib.
daySalesFigures = [[PBSDaySales alloc] init];
responseVal = [[HttpJsonResponse alloc] init];
// Use Grand Central Dispatch to run async task to server
dispatch_async(unirestQueue, ^{
[self runUnirestRequest:self.requestUrl];
});
dispatch_after(unirestQueue, dispatch_get_main_queue(), ^(void){
[activityIndicator stopAnimating];
});
}
runUniRestRequest function
- (void) runUnirestRequest:(NSString*)urlToGet
{
[NSThread sleepForTimeInterval:5.0];
NSLog(#"runUnirestRequest called");
HttpJsonResponse* response = [[Unirest get:^(SimpleRequest* request) {
[request setUrl:#"http://x.x.x.x:9000/Sales/Day/2013-02-14"];
}] asString];
NSString *jsonStr = [response body];
SBJsonParser *jsonParser = [SBJsonParser new];
id response2 = [jsonParser objectWithString:jsonStr];
[self deserializeJsonPacket:(NSDictionary*)response2];
}
dispatch_after's first parameter is time. You are passing in unirestQueue, which is dispatch_queue_t queue according to
unirestQueue = dispatch_queue_create("com.simpleweb.pbs.dayDataUnirestRequest", NULL);
proper code for dispatch_after, i.e. performing block after some delay, is like this:
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// Do whatever you want
});
Edit: Oh, I probably see what you are trying to accomplish :-) You thought the dispatch_after means "do something after this queue" right? Nope, it's "do something after some time"
Edit 2: You can use code like below to do something time consuming in background and update UI when its done
// Start block on background queue so the main thread is not frozen
// which prevents apps UI freeze
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do something taking a long time in background
// Here we just freeze current (background) thread for 5s
[NSThread sleepForTimeInterval:5.0];
// Everything in background thread is done
// Call another block on main thread to do UI stuff
dispatch_async(dispatch_get_main_queue(), ^{
// Here you are in the main thread again
// You can do whatever you want
// This example just stops UIActivityIndicatorView
[activityIndicator stopAnimating];
});
});
Edit 3: I recommend this great article about GCD at raywenderlich.com for more detailed info

Adding delay between execution of two following lines

I need to add a delay between the execution of two lines in a(same) function. Is there any favorable option to do this?
Note: I don't need two different functions to do this, and the delay must not affect other functions' execution.
eg:
line 1: [executing first operation];
line 2: Delay /* I need to introduce delay here */
line 3: [executing second operation];
You can use gcd to do this without having to create another method
// ObjC
NSTimeInterval delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(#"Do some work");
});
// Swift
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
print("Do some work)
}
You should still ask yourself "do I really need to add a delay" as it can often complicate code and cause race conditions
You can use the NSThread method:
[NSThread sleepForTimeInterval: delay];
However, if you do this on the main thread you'll block the app, so only do this on a background thread.
or in Swift
NSThread.sleepForTimeInterval(delay)
in Swift 3
Thread.sleep(forTimeInterval: delay)
This line calls the selector secondMethod after 3 seconds:
[self performSelector:#selector(secondMethod) withObject:nil afterDelay:3.0 ];
Use it on your second operation with your desired delay. If you have a lot of code, place it in its own method and call that method with performSelector:. It wont block the UI like sleep
Edit: If you do not want a second method you could add a category to be able to use blocks with performSelector:
#implementation NSObject (PerformBlockAfterDelay)
- (void)performBlock:(void (^)(void))block
afterDelay:(NSTimeInterval)delay
{
block = [block copy];
[self performSelector:#selector(fireBlockAfterDelay:)
withObject:block
afterDelay:delay];
}
- (void)fireBlockAfterDelay:(void (^)(void))block
{
block();
}
#end
Or perhaps even cleaner:
void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void))
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
dispatch_get_current_queue(), block);
}
I have a couple of turn-based games where I need the AI to pause before taking its turn (and between steps in its turn). I'm sure there are other, more useful, situations where a delay is the best solution. In Swift:
let delay = 2.0 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) { self.playerTapped(aiPlayView) }
I just came back here to see if the Objective-C calls were different.(I need to add this to that one, too.)
[checked 27 Nov 2020 and confirmed to be still accurate with Xcode 12.1]
The most convenient way these days: Xcode provides a code snippet to do this where you just have to enter the delay value and the code you wish to run after the delay.
click on the + button at the top right of Xcode.
search for after
It will return only 1 search result, which is the desired snippet (see screenshot). Double click it and you're good to go.
If you're targeting iOS 4.0+, you can do the following:
[executing first operation];
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[executing second operation];
});
Like #Sunkas wrote, performSelector:withObject:afterDelay: is the pendant to the dispatch_after just that it is shorter and you have the normal objective-c syntax. If you need to pass arguments to the block you want to delay, you can just pass them through the parameter withObject and you will receive it in the selector you call:
[self performSelector:#selector(testStringMethod:)
withObject:#"Test Test"
afterDelay:0.5];
- (void)testStringMethod:(NSString *)string{
NSLog(#"string >>> %#", string);
}
If you still want to choose yourself if you execute it on the main thread or on the current thread, there are specific methods which allow you to specify this. Apples Documentation tells this:
If you want the message to be dequeued when the run loop is in a mode
other than the default mode, use the
performSelector:withObject:afterDelay:inModes: method instead. If you
are not sure whether the current thread is the main thread, you can
use the performSelectorOnMainThread:withObject:waitUntilDone: or
performSelectorOnMainThread:withObject:waitUntilDone:modes: method to
guarantee that your selector executes on the main thread. To cancel a
queued message, use the cancelPreviousPerformRequestsWithTarget: or
cancelPreviousPerformRequestsWithTarget:selector:object: method.

What would be the equivalent of doing this with NSOperation?

[self performSelector:#selector(stopPulling) withObject:nil afterDelay:0.01];
The code is fine. I just think that using NSOperation and block should be the way to go for the future.
I am familiar with NSOperation. I just want to do the same thing with block and NSOperation.
I can do this with GCD already:
int64_t delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
<#code to be executed on the main queue after delay#>
});
C'mon. There is something that can be done in GCD that can't be done more easily in NSOperation?
NSOperationQueue does not provide a mechanism for delayed execution. Use GCD or NSTimer.
I ended up making this:
#import "BGPerformDelayedBlock.h"
#implementation BGPerformDelayedBlock
+ (void)performDelayedBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay
{
int64_t delta = (int64_t)(1.0e9 * delay);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delta), dispatch_get_main_queue(), block);
}
+(void)performSlightlyDelayedBlock:(void (^)(void))block
{
[self performDelayedBlock:block afterDelay:.1];
}
#end
It's based on an answer in How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?
I think it shouldn't be a category.
Strange that I ended up using GCD.
However, using it is simple. I just do:
[BGPerformDelayedBlock performSlightlyDelayedBlock:^{
[UIView animateWithDuration:.3 animations:^{
[self snapToTheTopOfTheNonHeaderView];
}];
}];
Your code is similar to, using a NSTimer setting a selector after 0.01sec with no repeats. This will be called on the main thread.
NSOperation or blocks are used to perform operations in background. These you can use instead of performSelectorInBackground.
If your need is to work in background then go for it. There are many tutorials available to learn 'NSOperationusing 'NSOperationQueue and blocks.

Objective-C: Too much recursion occurs with method swizzling on a background thread?

Disclaimer: This question is meant to be purely theoretical, so please don't ask me why I'm doing this.
If I have the following code:
- (void) beginCatastrophe {
double delayInSeconds = 3.5;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_global_queue(0, 0), ^(void){
Class cls = [self class];
IMP replacement = class_getMethodImplementation(cls, #selector(fooReplacement:));
Method fooMethod = class_getInstanceMethod(cls, #selector(foo:));
method_setImplementation(fooMethod, replacement);
});
[self foo:1];
}
- (void) fooReplacement:(unsigned) x {}
- (void) foo:(unsigned) x {
[self foo:++x];
}
And somewhere else in my code, I call -beginCatastrophe
This results in a "too much recursion" error. Why?
I have confirmed that the swizzling code works after 2 seconds, but not any more than
that.
However, if I do something like this:
- (void) beginCatastrophe {
double delayInSeconds = 3.5;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_global_queue(0, 0), ^(void){
Class cls = [self class];
IMP replacement = class_getMethodImplementation(cls, #selector(fooReplacement:));
Method fooMethod = class_getInstanceMethod(cls, #selector(foo:));
method_setImplementation(fooMethod, replacement);
});
[self foo:nil];
}
- (void) fooReplacement:(id) x {
printf("%s", _cmd);
}
- (void) foo:(id) x {
[self performSelector:_cmd withObject:x afterDelay:0.00001];
}
This, of course works fine no matter how long I make the delayInSeconds.
This is only a guess, but I would guess that your stack is being exhausted well before that background task fires. You have it set to fire 3.5 seconds from now, then you continue on and recursively call foo. 3.5 seconds will put a ton of frames on the stack and will exhaust it before the method is swizzled.
If it's not this, then perhaps it is an issue with how this dispatch works with your runloop. You never do exit that beginCatastrophe method so the runloop never gets a chance to turn once you call it. Perhaps the swizzling thread never gets called? If you put a log statement in fooReplacement: does it get called?