How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

πŸ“πŸ‘€πŸ“’ Are you curious about how to trigger a block after a delay, just like the mighty performSelector: withObject: afterDelay: method? πŸ€”πŸ’­ Well, buckle up, my fellow tech enthusiasts, because today we're diving into the world of delayed block execution with primitive parameters! πŸš€πŸ”§

So, picture this scenario: you want to call a block that takes a primitive parameter, like int, double, or float, but you also want it to execute after a certain delay. πŸ•’β° You might think this is a job exclusively for performSelector: withObject: afterDelay:, which sadly doesn't support primitive parameters. 😒

But fret not! I have two super cool solutions in my tech toolbox that will make your programming life easier than ever! πŸ’ͺπŸ› οΈ

1️⃣ Solution number one: good ol' dispatch_after to the rescue! 🚁πŸͺ“ This nifty asynchronous Grand Central Dispatch (GCD) function can execute a block after a specified delay. And the best part? It can handle those pesky primitive parameters like a champ! πŸ’₯πŸŒͺ️

Here's a neat code snippet to get you started:

int myPrimitiveParameter = 42;
double delayInSeconds = 2.5;

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    // Your awesome block code goes here, with access to `myPrimitiveParameter`
});

And just like that, your block will be executed after the specified delay, with your primitive parameter ready for action! πŸŽ‰πŸ‹οΈβ€β™€οΈ

2️⃣ Not a fan of GCD? No worries, there's another approach for you! 😎🀘 You can create a category on NSObject to add a method that takes a block with primitive parameters and executes it after a delay. πŸŒŸπŸ› οΈ

Here's a quick example to help you get started:

// NSObject+DelayBlock.h
#import <Foundation/Foundation.h>

@interface NSObject (DelayBlock)
- (void)performBlock:(void (^)(void))block withObject:(id)parameter afterDelay:(NSTimeInterval)delay;
@end

// NSObject+DelayBlock.m
#import "NSObject+DelayBlock.h"

@implementation NSObject (DelayBlock)
- (void)performBlock:(void (^)(void))block withObject:(id)parameter afterDelay:(NSTimeInterval)delay {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (block) {
            block(parameter);
        }
    });
}
@end

And now, you can use this method just like you would use performSelector: withObject: afterDelay:, but with the added support for primitive parameters! πŸ™ŒπŸ”§

int myPrimitiveParameter = 42;
double delayInSeconds = 2.5;

[self performBlock:^(void){
    // Your amazing block code goes here, with access to `myPrimitiveParameter`
} withObject:@(myPrimitiveParameter) afterDelay:delayInSeconds];

Your block will be executed after the specified delay, with your primitive parameter intact and ready to rock! 🎸🎀

Now that you have two awesome solutions in your tech arsenal, go forth and conquer the world of delayed block execution with primitive parameters! πŸŒπŸš€ But don't stop there! Share your wisdom in the comments below and let's dive into even more ways to tackle this problem. Together, we can level up our coding skills! πŸ’ͺπŸ’»βœ¨

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

πŸ”₯ πŸ’» πŸ†’ Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! πŸš€ Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings πŸ’₯βœ‚οΈ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide πŸš€ So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? πŸ€” Well, my