2009-05-28 45 views

Trả lời

20

Bạn sẽ làm gì

[self performSelectorInBackground:@selector(heavyStuff) withObject:nil]; 

Xem NSObject reference trên trang web của Apple.

4

Bạn có thể sử dụng NSOperationQueue và NSInvocationOperation:

[self myFoo]; 

NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init]; 
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self                 selector:@selector(heavyStuff) object:nil]; 
[operationQueue addOperation:operation]; 

[self myBar]; 
15

Đối với "lửa và quên", hãy thử [self performSelectorInBackground:@selector(heavyStuff) withObject:nil]. Nếu bạn có nhiều thao tác như thế này, bạn có thể muốn xem NSOperation và lớp con của nó NSInvocationOperation. NSOperationQueue quản lý sợi tổng hợp, số lượng đồng thời thực hiện các hoạt động và bao gồm thông báo hoặc ngăn chặn các phương pháp để cho bạn biết khi tất cả các hoạt động hoàn chỉnh:

[self myFoo]; 

NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init]; 
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self                                 selector:@selector(heavyStuff) object:nil]; 

[operationQueue addOperation:operation]; 
[operation release]; 

[self myBar]; 

... 

[operationQueue waitUntilAllOperationsAreFinished]; //if you need to block until operations are finished 

Ở mức độ thấp hơn, bạn có thể sử dụng sử dụng -[NSThread detachNewThreadSelector:@selector(heavyStuff) toTarget:self withObject:nil].

+0

thiếu 'g' trong performSelectorInBackround – Erich

+0

cố định. cảm ơn @Erich. –

7

Bạn có nhiều gợi ý tuyệt vời ở đây, nhưng đừng quên dành chút thời gian với Threading Programming Guide. Nó cung cấp hướng dẫn tốt không chỉ trên các công nghệ, mà còn thiết kế tốt xử lý đồng thời, và làm thế nào để sử dụng tốt hơn vòng lặp chạy cả với các chủ đề và thay vì các luồng.

7

Nếu bạn đang nhắm mục tiêu Snow Leopard dành riêng, bạn có thể sử dụng Grand Central Dispatch:

[self myFoo]; 
dispatch_async(dispatch_get_global_queue(0, 0), ^{ 
    [self heavyStuff]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self myBar]; 
    }); 
}); 

Nhưng nó sẽ không chạy trên các hệ thống trước đó (hoặc iPhone) và có lẽ là quá mức cần thiết.

EDIT: hoạt động trên iPhone từ iOS 4.x.

+0

NSOperation cũng sử dụng GCD trong Snow Leopard, và nó bao gồm một lớp con NSBlockOperation để bạn có thể sử dụng các khối với nó. – Chuck

Các vấn đề liên quan