0Pricing
Objective-C iOS Development for Legacy & Enterprise Apps · درس

التوزيع المركزي الكبير (GCD)

طبّقوا عمليات متزامنة باستخدام Grand Central Dispatch لتحسين استجابة التطبيق وأدائه.

التوزيع المركزي الكبير (GCD) درس مجاني في Objective-C iOS Development for Legacy & Enterprise Apps على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Objective-C iOS Development for Legacy & Enterprise Apps، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Objective-C iOS Development for Legacy & Enterprise Apps 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Keeping Apps Responsive

Ever used an app that froze when loading data? That's often due to blocking the main thread.

The main thread is where all UI updates and user interactions happen. If you perform a long-running task there, your app becomes unresponsive.

Concurrency means running multiple tasks seemingly at the same time. This keeps the main thread free, ensuring a smooth user experience.

Meet GCD

Grand Central Dispatch (GCD) is Apple's powerful low-level API for managing concurrent operations. It's built on top of C and blocks, and makes it easy to perform tasks asynchronously.

GCD helps you run code concurrently by managing dispatch queues. You tell GCD what tasks to run, and it decides when and how to execute them on available processor cores.

Understanding Dispatch Queues

GCD uses dispatch queues to manage tasks. Think of a queue as a line of tasks waiting to be executed.

  • Serial Queues: Tasks run one by one, in the order they were added. Each serial queue processes its tasks sequentially.
  • Concurrent Queues: Tasks are started in the order they are added, but can run at the same time (concurrently). The order of completion is not guaranteed.

The UI's Best Friend

Every iOS application has a special serial queue called the main dispatch queue. This is where all UI updates must happen.

If you try to update the UI from a background thread, your app might crash or behave unexpectedly. Always switch back to the main queue for UI changes.

You access it using dispatch_get_main_queue().

System's Background Helpers

GCD provides several global concurrent queues that you can use for background tasks. These queues are managed by the system and optimized for performance.

They differ by their Quality of Service (QoS) class, which indicates the priority of tasks:

  • .userInteractive: UI-related, highest priority.
  • .userInitiated: User-requested tasks.
  • .utility: Long-running, non-urgent tasks.
  • .background: Maintenance, lowest priority.

Background Work Made Easy

The most common way to use GCD is with dispatch_async. This function adds a task (a block of code) to a queue and immediately returns, allowing the calling code to continue execution.

The task will then run on a separate thread in the background. This is perfect for operations that don't need to block the main thread, like network requests or heavy computations.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    NSLog(@"1. Program starts.");

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      NSLog(@"3. Doing some background work...");
      [NSThread sleepForTimeInterval:1.0]; // Simulate work
      NSLog(@"4. Background work finished.");
    });

    NSLog(@"2. Program continues immediately after dispatch_async.");
    [NSThread sleepForTimeInterval:2.0]; // Keep main thread alive
  }
  return 0;
}

Waiting for a Task

While dispatch_async is great for non-blocking operations, sometimes you need to wait for a task to complete before continuing. That's where dispatch_sync comes in.

dispatch_sync adds a task to a queue and then blocks the current thread until that task finishes execution. Be careful: never call dispatch_sync on the current queue, as it will cause a deadlock!

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    NSLog(@"1. Program starts.");

    dispatch_queue_t mySerialQueue = dispatch_queue_create("com.coddykit.myserialqueue", DISPATCH_QUEUE_SERIAL);

    dispatch_sync(mySerialQueue, ^{
      NSLog(@"2. This synchronous task runs now.");
      [NSThread sleepForTimeInterval:0.5];
    });

    NSLog(@"3. Program continues AFTER the synchronous task completes.");
  }
  return 0;
}

Seamless UI Updates

A common pattern in iOS apps is to perform a long-running task in the background and then update the UI once it's done. This prevents the UI from freezing.

You achieve this by dispatching the background task to a global concurrent queue, and then dispatching the UI update task to the main queue.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    NSLog(@"1. App starts, fetching data...");

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      NSLog(@"2. Performing heavy data fetch on background thread...");
      [NSThread sleepForTimeInterval:1.5]; // Simulate network call or heavy computation
      NSString *fetchedData = @"User Data Loaded!";

      dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"3. Data fetched! Updating UI on main thread: %@", fetchedData);
        // In a real app, you'd update a UILabel or UIImageView here.
      });
    });

    NSLog(@"4. App remains responsive while data fetches.");
    [NSThread sleepForTimeInterval:2.0]; // Keep main thread alive
  }
  return 0;
}

Scheduling Tasks Later

Sometimes you need to schedule a task to run after a certain delay. GCD provides dispatch_after for this purpose.

It's important to note that dispatch_after is not a real-time timer. It simply adds a block to the specified queue after a minimum delay. The exact execution time depends on the queue's activity.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    NSLog(@"1. Program starts.");
    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(), ^{
      NSLog(@"2. This message appears after 2 seconds.");
    });

    NSLog(@"3. Program continues immediately, waiting for delayed task.");
    [NSThread sleepForTimeInterval:3.0]; // Keep main thread alive
  }
  return 0;
}

GCD Check-up

Let's test your understanding of GCD.

GCD Summary

Great job! You've learned the fundamentals of Grand Central Dispatch.

  • GCD helps manage concurrent tasks to keep your app responsive.
  • Dispatch queues (serial and concurrent) control task execution.
  • The main queue is for UI updates, always accessed via dispatch_async.
  • Global concurrent queues are for background work.
  • dispatch_async runs tasks without blocking, dispatch_sync waits for tasks.

Mastering GCD is crucial for building high-performance, responsive iOS applications.

الأسئلة الشائعة

هل درس «التوزيع المركزي الكبير (GCD)» مجاني؟

نعم — نص درس «التوزيع المركزي الكبير (GCD)» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Objective-C iOS Development for Legacy & Enterprise Apps، انتقل إلى CoddyKit PRO. تتضمن دورة Objective-C iOS Development for Legacy & Enterprise Apps 4 دروس في المجموع.

ماذا ستتعلم في «التوزيع المركزي الكبير (GCD)»؟

طبّقوا عمليات متزامنة باستخدام Grand Central Dispatch لتحسين استجابة التطبيق وأدائه. تتمرن على Objective-C iOS Development for Legacy & Enterprise Apps مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Objective-C iOS Development for Legacy & Enterprise Apps؟

لا تُشترط خبرة سابقة. Objective-C iOS Development for Legacy & Enterprise Apps على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «التوزيع المركزي الكبير (GCD)»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Objective-C iOS Development for Legacy & Enterprise Apps هذا؟

نعم. كل درس في Objective-C iOS Development for Legacy & Enterprise Apps يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. ‏NSURLSession لاستدعاءات API
  2. التوزيع المركزي الكبير (GCD)
  3. ‏NSOperationQueue للمهام المعقدة
  4. تحليل JSON باستخدام NSJSONSerialization
← العودة إلى Objective-C iOS Development for Legacy & Enterprise Apps