NSOperation

1.最近项目中有使用到了我们苹果大力推荐的NSOperation,我们都知道NSOperation其实是没有任何用的,因为他是一个抽象类。所以我们使用它的子类来做开辟线程,用NSOperationQueue来管理线程。

2.1 NSOperation的子类NSBlockOperation:

@interface NSBlockOperation : NSOperation {
@private
    id _private2;
    void *_reserved2;
}
//使用这个方法设置线程
+ (instancetype)blockOperationWithBlock:(void (^)(void))block;

- (void)addExecutionBlock:(void (^)(void))block;
@property (readonly, copy) NSArray<void (^)(void)> *executionBlocks;

@end

 2.2 NSOperation的子类NSInvocationOperation:

@interface NSInvocationOperation : NSOperation {
@private
    id _inv;
    id _exception;
    void *_reserved2;
}
//使用NSInvocationOperation创建对象,使用此方法调用方法中的创建的方法
- (nullable instancetype)initWithTarget:(id)target selector:(SEL)sel object:(nullable id)arg;
- (instancetype)initWithInvocation:(NSInvocation *)inv NS_DESIGNATED_INITIALIZER;

@property (readonly, retain) NSInvocation *invocation;

@property (nullable, readonly, retain) id result;

@end

2.3 NSOperationQueue用于线程管理:@interface NSOperationQueue : NSObject {

@private
    id _private;
    void *_reserved;
}
//将任务放入队列中
- (void)addOperation:(NSOperation *)op;
//将任务集合数组放入队列中,在将几何数组任务执行完之前,不在执行队列里添加的其他任务
- (void)addOperations:(NSArray<NSOperation *> *)ops waitUntilFinished:(BOOL)wait NS_AVAILABLE(10_6, 4_0); //直接将任务放到队列中(在队列中从新创建任务) - (void)addOperationWithBlock:(void (^)(void))block NS_AVAILABLE(10_6, 4_0); @property (readonly, copy) NSArray<__kindof NSOperation *> *operations; @property (readonly) NSUInteger operationCount NS_AVAILABLE(10_6, 4_0); //最大并发数(限制线程的个数) @property NSInteger maxConcurrentOperationCount; //suspened:暂停。即为将线程挂起 @property (getter=isSuspended) BOOL suspended; // @property (nullable, copy) NSString *name NS_AVAILABLE(10_6, 4_0); //线程优先级:使用优先级可以设置线程执行顺序
NSQualityOfServiceUserInteractive = 0x21,
NSQualityOfServiceUserInitiated = 0x19,
NSQualityOfServiceUtility = 0x11,
NSQualityOfServiceBackground = 0x09,
@property NSQualityOfService qualityOfService NS_AVAILABLE(10_10, 8_0);

@property (nullable, assign /* actually retain */) dispatch_queue_t underlyingQueue NS_AVAILABLE(10_10, 8_0);

- (void)cancelAllOperations;

- (void)waitUntilAllOperationsAreFinished;

+ (nullable NSOperationQueue *)currentQueue NS_AVAILABLE(10_6, 4_0);
//获取主队列(我们一般在子线程进行耗时操作,在主线程中更新UI)
+ (NSOperationQueue *)mainQueue NS_AVAILABLE(10_6, 4_0);

NSOperation 还可以自定义子类。

 

posted @ 2016-03-31 10:56  王侯将相宁有种乎?  阅读(280)  评论(0)    收藏  举报