NSOperationQueue สำหรับงานที่ซับซ้อน
สำรวจ NSOperation และ NSOperationQueue เพื่อการทำงานพร้อมกันที่มีโครงสร้างและจัดการได้ง่ายขึ้น รวมถึงการกำหนดลำดับพึ่งพา
NSOperationQueue สำหรับงานที่ซับซ้อน เป็นบทเรียน Objective-C iOS Development for Legacy & Enterprise Apps ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Objective-C iOS Development for Legacy & Enterprise Apps และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Objective-C iOS Development for Legacy & Enterprise Apps มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why NSOperationQueue?
You've learned about Grand Central Dispatch (GCD) for concurrent tasks. While powerful, GCD can become complex for intricate task management.
NSOperationQueue offers a higher-level, object-oriented way to handle concurrency. It builds on top of GCD, providing more control and features like dependencies, cancellation, and state management.
What is NSOperation?
At the core of NSOperationQueue is NSOperation. It's an abstract class representing a single unit of work that can be executed concurrently.
You don't instantiate NSOperation directly. Instead, you use its concrete subclasses or create your own custom subclasses to define specific tasks.
- Encapsulates work: Each operation is a self-contained task.
- Manages state: Operations have states like "ready," "executing," "finished."
- Supports dependencies: Operations can depend on others completing first.
Build Your Own Operation
To create a custom operation, you subclass NSOperation and override its main method. This is where your task's logic goes.
Remember to mark your operation as "finished" when done, especially for asynchronous operations. For synchronous operations, main handles it.
Try running this simple custom operation:
#import <Foundation/Foundation.h>
// CustomOperation.h
@interface CustomOperation : NSOperation
@end
// CustomOperation.m
@implementation CustomOperation
- (void)main {
if (self.isCancelled) {
return; // Always check for cancellation
}
NSLog(@"Custom operation started!");
// Simulate some work
[NSThread sleepForTimeInterval:1.0];
NSLog(@"Custom operation finished!");
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
CustomOperation *op = [[CustomOperation alloc] init];
[op start]; // Manually start for demo
}
return 0;
}Simple Tasks with BlockOperation
For simpler tasks that don't require a custom subclass, NSBlockOperation is perfect. It allows you to wrap one or more blocks of code as an operation.
This is often used for quick, one-off tasks without the overhead of creating a new class.
Here's how to use it:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSBlockOperation *blockOp = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Block operation running!");
[NSThread sleepForTimeInterval:0.5];
NSLog(@"Block operation done!");
}];
[blockOp start]; // Manually start for demo
}
return 0;
}Executing with NSOperationQueue
To truly leverage concurrency, you add operations to an NSOperationQueue. The queue manages the execution of operations, often concurrently.
The queue decides when to start operations based on their readiness and dependencies. It handles the threading for you.
Observe how both operations run concurrently:
#import <Foundation/Foundation.h>
@interface CustomOperation : NSOperation
@end
@implementation CustomOperation
- (void)main {
if (self.isCancelled) return;
NSLog(@"Custom operation started!");
[NSThread sleepForTimeInterval:1.0];
NSLog(@"Custom operation finished!");
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
CustomOperation *op1 = [[CustomOperation alloc] init];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Block operation started!");
[NSThread sleepForTimeInterval:0.5];
NSLog(@"Block operation finished!");
}];
[queue addOperation:op1];
[queue addOperation:op2];
// Wait for all operations to complete
[queue waitUntilAllOperationsAreFinished];
NSLog(@"All operations completed!");
}
return 0;
}Chaining Tasks with Dependencies
One of NSOperation's most powerful features is setting dependencies. An operation can be configured to only start after another specific operation (or set of operations) has finished.
This is crucial for tasks that must be executed in a particular order, ensuring data consistency or proper workflow.
Notice how "Op B" waits for "Op A":
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSBlockOperation *opA = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Operation A running...");
[NSThread sleepForTimeInterval:1.0];
NSLog(@"Operation A done!");
}];
NSBlockOperation *opB = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Operation B running...");
[NSThread sleepForTimeInterval:0.5];
NSLog(@"Operation B done!");
}];
// Op B depends on Op A
[opB addDependency:opA];
[queue addOperation:opA];
[queue addOperation:opB];
[queue waitUntilAllOperationsAreFinished];
NSLog(@"All dependent operations completed!");
}
return 0;
}Stopping Tasks Gracefully
Operations can be cancelled, which is vital for user-initiated stops or when a task becomes irrelevant.
When an operation is cancelled, its isCancelled property becomes YES. Your main method (or block) should regularly check this property and exit gracefully if it's true.
An operation that has already started might still complete some work before checking isCancelled.
#import <Foundation/Foundation.h>
@interface CancellableOperation : NSOperation
@end
@implementation CancellableOperation
- (void)main {
for (int i = 0; i < 5; i++) {
if (self.isCancelled) {
NSLog(@"Operation was cancelled early!");
return;
}
NSLog(@"Working... %d", i);
[NSThread sleepForTimeInterval:0.2];
}
NSLog(@"Operation finished normally.");
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
CancellableOperation *op = [[CancellableOperation alloc] init];
[queue addOperation:op];
// Wait a short time then try to cancel
[NSThread sleepForTimeInterval:0.3];
[op cancel];
NSLog(@"Attempted to cancel operation.");
[queue waitUntilAllOperationsAreFinished];
NSLog(@"Queue finished.");
}
return 0;
}Post-Execution Actions
Sometimes you need to perform an action only after an operation has finished, regardless of whether it succeeded or was cancelled.
Every NSOperation has a completionBlock property. This block is executed on an arbitrary thread once the operation's main method (or blocks for NSBlockOperation) has completed.
Use it for cleanup or to update the UI (remember to dispatch UI updates to the main thread!).
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"Operation running...");
[NSThread sleepForTimeInterval:0.5];
}];
op.completionBlock = ^{
NSLog(@"Operation completion block executed!");
// If updating UI, dispatch to main thread:
// dispatch_async(dispatch_get_main_queue(), ^{ /* UI update */ });
};
[queue addOperation:op];
[queue waitUntilAllOperationsAreFinished];
NSLog(@"All done!");
}
return 0;
}Managing Parallelism
An NSOperationQueue can execute multiple operations concurrently. You can control this behavior using the maxConcurrentOperationCount property.
1: Operations run serially (one at a time).NSOperationQueueDefaultMaxConcurrentOperationCount(usually -1): The queue decides the optimal number based on system conditions.- Any positive integer: Limits the number of operations running simultaneously.
This helps prevent resource exhaustion and manage workload.
Check Your Understanding
Test your knowledge on NSOperation and NSOperationQueue.
NSOperationQueue Recap
Great job! You've explored NSOperation and NSOperationQueue.
- NSOperation represents a single unit of work.
- NSOperationQueue manages the execution of operations, providing a higher-level abstraction over GCD.
- Key features include dependencies, cancellation, completion blocks, and control over concurrency.
- Use
NSBlockOperationfor simple tasks and custom subclasses for complex, reusable operations.
This powerful framework helps you build robust and manageable concurrent applications.
คำถามที่พบบ่อย
บทเรียน “NSOperationQueue สำหรับงานที่ซับซ้อน” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “NSOperationQueue สำหรับงานที่ซับซ้อน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Objective-C iOS Development for Legacy & Enterprise Apps ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Objective-C iOS Development for Legacy & Enterprise Apps มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “NSOperationQueue สำหรับงานที่ซับซ้อน”
สำรวจ NSOperation และ NSOperationQueue เพื่อการทำงานพร้อมกันที่มีโครงสร้างและจัดการได้ง่ายขึ้น รวมถึงการกำหนดลำดับพึ่งพา คุณปฏิบัติ Objective-C iOS Development for Legacy & Enterprise Apps ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Objective-C iOS Development for Legacy & Enterprise Apps หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Objective-C iOS Development for Legacy & Enterprise Apps บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “NSOperationQueue สำหรับงานที่ซับซ้อน” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Objective-C iOS Development for Legacy & Enterprise Apps นี้ได้ไหม
ได้ บทเรียน Objective-C iOS Development for Legacy & Enterprise Apps ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- NSURLSession สำหรับการเรียก API
- Grand Central Dispatch (GCD)
- NSOperationQueue สำหรับงานที่ซับซ้อน
- การแยกวิเคราะห์ JSON ด้วย NSJSONSerialization