<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Emre Gemici on Medium]]></title>
        <description><![CDATA[Stories by Emre Gemici on Medium]]></description>
        <link>https://medium.com/@gemiciemre?source=rss-7382c1369b5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lUQBZx26jqv3C9oU1dOotA.jpeg</url>
            <title>Stories by Emre Gemici on Medium</title>
            <link>https://medium.com/@gemiciemre?source=rss-7382c1369b5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:59:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gemiciemre/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Grand Central Dispatch (GCD)]]></title>
            <link>https://medium.com/@gemiciemre/grand-central-dispatch-gcd-8103e77c34df?source=rss-7382c1369b5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8103e77c34df</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[gcd]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[grand-central-dispatch]]></category>
            <dc:creator><![CDATA[Emre Gemici]]></dc:creator>
            <pubDate>Thu, 07 Aug 2025 17:22:54 GMT</pubDate>
            <atom:updated>2025-08-07T17:22:54.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yh9CtWR0eLnu50FbA2ECSw.png" /><figcaption>Creator: Author by Canva</figcaption></figure><h3>Grand Central Dispatch (GCD) Explained: Simplifying Concurrency in iOS</h3><p><strong>Grand Central Dispatch</strong> makes handling multiple tasks in iOS apps much easier than traditional threading approaches. Whether you’re loading data in the background, updating the UI, or syncing files to the cloud, GCD has your back.</p><h3>Key Takeaways</h3><ul><li><strong>Queue Types</strong>: Main queue runs on the UI thread, global queues handle background work.</li><li><strong>Sync vs Async</strong>: Sync blocks the current thread, async doesn’t wait for completion.</li><li><strong>Quality of Service</strong>: Use different priority levels for different kinds of tasks.</li><li><strong>Dispatch Groups</strong>: Run multiple async tasks in parallel and wait for all to finish.</li><li><strong>Serial vs Concurrent</strong>: Serial queues execute tasks one at a time; concurrent queues run tasks in parallel.</li></ul><h3>What is Grand Central Dispatch?</h3><p>Grand Central Dispatch (GCD) is Apple’s solution for managing concurrency in iOS and macOS apps. Instead of manually managing threads, you submit work to <em>queues</em>, and GCD handles the underlying complexity.</p><blockquote><em>Think of it like a restaurant kitchen</em></blockquote><h3>Understanding Queues</h3><h4>Main Queue</h4><p>The <strong>Main Queue</strong> is a special, <strong>serial dispatch queue</strong> provided by the system that is dedicated to handling all tasks related to <strong>updating the user interface (UI)</strong>. In iOS development, any task that affects UI components — such as modifying labels, updating views, or presenting view controllers — <strong>must</strong> be executed on this queue to avoid undefined behavior or crashes.</p><p>Because it’s a <strong>serial queue</strong>, tasks submitted to the main queue are executed <strong>one at a time</strong>, in the order they were added. This is crucial for maintaining a smooth and predictable user experience, as concurrent access to UI elements can cause conflicts or race conditions.</p><pre>DispatchQueue.global(qos: .background).async {<br>    // Perform a background task (e.g., fetching data from the network)<br>    let result = fetchDataFromNetwork()<br><br>    // Update the UI on the main queue<br>    DispatchQueue.main.async {<br>        self.label.text = result.title<br>    }<br>}</pre><h4>Global Queues</h4><p><strong>Global Queues</strong> are system-provided <strong>concurrent dispatch queues</strong> used for performing tasks in the background. Unlike the main queue, they allow multiple tasks to run in parallel, making them ideal for non-UI work such as data processing, network requests, or file I/O.</p><p>Apple provides several global queues, each associated with a specific <strong>Quality of Service (QoS)</strong> level. QoS helps the system prioritize tasks based on their importance and urgency. Common QoS levels include:</p><ul><li>.<strong>userInitiated</strong>: For tasks the user is actively waiting on.</li><li>.<strong>utility</strong>: For longer-running tasks like downloads or calculations.</li><li>.<strong>background</strong>: For non-urgent tasks like syncing or pre-fetching.</li><li>.<strong>userInteractive</strong>: For high-priority tasks that affect the UI immediately.</li></ul><pre>// Highest Priority – For UI-related tasks that need to be done immediately<br>DispatchQueue.global(qos: .userInteractive).async {<br>    // Tasks that need to run instantly to keep UI responsive (e.g., animations)<br>}<br><br>// High Priority – For tasks the user is actively waiting for<br>DispatchQueue.global(qos: .userInitiated).async {<br>    // Important background task (e.g., loading data after a button tap)<br>}<br><br>// Medium Priority – For long-running tasks that don’t need immediate results<br>DispatchQueue.global(qos: .utility).async {<br>    // Utility tasks like downloading files, processing data, etc.<br>}<br><br>// Low Priority – For tasks the user doesn’t need to know about<br>DispatchQueue.global(qos: .background).async {<br>    // Maintenance tasks like syncing, backups, or pre-fetching data<br>}<br><br>// Default Priority – Used when no QoS is specified<br>DispatchQueue.global().async {<br>    // Default priority task<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ze1eQxwV__gmpD_MCXywNw.png" /><figcaption>Creator: Author by Canva</figcaption></figure><h4>Custom Queues</h4><p>While the system provides default queues like the main and global queues, you can also create <strong>custom dispatch queues</strong> tailored to your app’s specific needs. Custom queues give you fine-grained control over task execution, allowing you to define whether tasks run <strong>serially</strong> (one after another) or <strong>concurrently</strong> (in parallel).</p><p>Creating a <strong>serial queue</strong> (default behavior):</p><pre>let customQueue = DispatchQueue(label: &quot;com.myapp.serial&quot;)<br><br>customQueue.async {<br>    // Task 1<br>}<br>customQueue.async {<br>    // Task 2 (runs after Task 1)<br>}.concurren</pre><p>Creating a <strong>concurrent queue</strong>:</p><pre>let concurrentQueue = DispatchQueue(label: &quot;com.myapp.concurrent&quot;, attributes: .concurrent)<br><br>concurrentQueue.async {<br>    // Task A<br>}<br>concurrentQueue.async {<br>    // Task B (can run in parallel with Task A)<br>}</pre><p>Custom queues are especially useful when you want to manage synchronization manually, isolate certain tasks (e.g., logging or caching), or prevent contention with other queues.</p><p>By naming your queues meaningfully (e.g., com.myapp.networking), you also make debugging and performance profiling easier.</p><h3>Sync vs Async: The Big Difference</h3><h4>Asynchronous (async)</h4><ul><li>Returns immediately</li><li><strong>Doesn’t block</strong> current thread</li><li>Runs in the background</li><li>Great for non-UI work</li></ul><pre>DispatchQueue.global().async {<br>    print(&quot;Background work&quot;)<br>}<br>print(&quot;This prints first&quot;)<br><br>// Output:<br>// This prints first<br>// Background work</pre><blockquote><em>When you use async, the task starts but your code continues executing without waiting for it to finish. You typically update the UI later on the main queue once the task completes.</em></blockquote><h4>Synchronous (sync)</h4><ul><li>Waits for task completion</li><li>Blocks the current thread</li><li>⚠️ <strong>Never use on the main queue</strong> — can freeze your UI</li><li>Useful for very short, critical tasks on background threads</li></ul><pre>DispatchQueue.global().sync {<br>    print(&quot;Background work&quot;)<br>}<br>print(&quot;This prints second&quot;)<br><br>// Output: <br>// Background work<br>// This prints second</pre><blockquote><em>sync stops the current thread until the task is complete. If used on the main thread, it can cause the app to become unresponsive or even crash due to a deadlock.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQJGANJQklEY5hiBtSLnWA.png" /><figcaption>Creator: Author by Canva</figcaption></figure><h3>🚦Dispatch Groups: Wait for Multiple Tasks</h3><p>When working with asynchronous tasks — such as fetching multiple images, performing API calls, or loading local resources — you often need to <strong>wait until all tasks are finished before proceeding</strong>. This is where <strong>DispatchGroup</strong> becomes a powerful tool.</p><p>Let’s look at an example and break it down:</p><pre>let group = DispatchGroup()<br><br>group.enter()<br>downloadImage1 { image in<br>    // Do something with image1<br>    group.leave()<br>}<br><br>group.enter()<br>downloadImage2 { image in<br>    // Do something with image2<br>    group.leave()<br>}<br><br>group.notify(queue: .main) {<br>    updateUI()<br>}</pre><h4>Use Cases</h4><ul><li>Downloading multiple resources in parallel</li><li>Executing a group of API calls before continuing</li><li>Waiting for multiple animations or transitions to complete</li><li>Loading cached files or local data before launching a screen</li></ul><h3>Common Patterns &amp; Best Practices</h3><h4>Heavy Work + UI Update</h4><pre>DispatchQueue.global().async {<br><br>  let result = processLargeDataSet()<br>  <br>  DispatchQueue.main.async {<br>       self.displayResult(result)<br>  }<br>}</pre><h4>Delay Execution</h4><pre>DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {<br>    hideLoadingSpinner()<br>}</pre><h4>Serial Queue for Data Safety</h4><pre>let dataQueue = DispatchQueue(label: &quot;data.queue&quot;)<br><br>func updateData() {<br>    dataQueue.async {<br>        self.sharedData.append(newItem)<br>    }<br>}</pre><h3>What to Avoid</h3><h4>❌ Blocking the Main Thread</h4><pre>// ❌ Don&#39;t do this<br>DispatchQueue.main.async {<br>    processHugeFile() // UI freezes<br>}<br><br>// ✅ Instead<br>DispatchQueue.global().async {<br>    let result = processHugeFile()<br>    DispatchQueue.main.async {<br>        displayResult(result)<br>    }<br>}</pre><h4>❌ Sync Main Queue</h4><pre>// ❌ Deadlock!<br>DispatchQueue.main.sync {<br>    // App freezes<br>}</pre><h4>❌ Too Many Queues</h4><p>Stick with global queues unless you need strict control. GCD is optimized — don’t over-engineer it.</p><h3>Real-World Example</h3><pre>func loadUserProfile(userId: String) {<br>    DispatchQueue.main.async {<br>        self.showLoadingSpinner()<br>    }<br><br>    DispatchQueue.global(qos: .userInitiated).async {<br>        let profile = APIClient.fetchProfile(userId: userId)<br>        let avatar = APIClient.fetchAvatar(userId: userId)<br>        DispatchQueue.main.async {<br>            self.hideLoadingSpinner()<br>            self.displayProfile(profile)<br>            self.displayAvatar(avatar)<br>        }<br>    }<br>}</pre><h3>Wrapping Up</h3><p>Grand Central Dispatch takes the headache out of multi-threaded programming in iOS. With a few basic patterns, you can write responsive, efficient apps without dealing with the complexity of raw threads.</p><h3>Final Tips:</h3><ul><li>Use .async for background work.</li><li>Always update UI on the <strong>main queue</strong>.</li><li>Pick the right <strong>QoS</strong> level for the job.</li><li>Use <strong>dispatch groups</strong> to sync multiple async tasks.</li><li>Keep it simple — don’t overuse custom queues.</li></ul><blockquote><em>💡 </em><strong><em>Pro Tip</em></strong></blockquote><blockquote><em>If you found this guide helpful, consider sharing it with your fellow developers or bookmarking it for future reference. Happy coding! 💻</em></blockquote><h3>Sources</h3><ul><li><a href="https://developer.apple.com/documentation/dispatch">Dispatch | Apple Developer Documentation</a></li><li><a href="https://en.wikipedia.org/wiki/Grand_Central_Dispatch">Grand Central Dispatch - Wikipedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8103e77c34df" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>