2014-10-15 2 views
0

Я хочу создать одновременно 2 операции. Он постоянно создает объект и добавляет его в очередь с интервалом 15 мс. Другая операция постоянно удаляет 1-й элемент из очереди с интервалом 10 мс.Как создать 2 операции с использованием NSOperationQueue

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // Uncomment the following line to preserve selection between presentations. 
    // self.clearsSelectionOnViewWillAppear = NO; 

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 
    // self.navigationItem.rightBarButtonItem = self.editButtonItem; 

    _arrInformations = [[NSMutableArray alloc] init]; 

    queue = [NSOperationQueue new]; 

    // start continuous processing 
    [NSTimer scheduledTimerWithTimeInterval:0.15 
            target:self 
            selector:@selector(addNewInformation) 
            userInfo:nil 
            repeats:YES]; 

    [NSTimer scheduledTimerWithTimeInterval:0.1 
            target:self 
            selector:@selector(removeInformation) 
            userInfo:nil 
            repeats:YES]; 
} 

-(void)addNewInformation { 
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(addDataWithOperation) object:nil]; 
    /* Add the operation to the queue */ 
    [queue addOperation:operation]; 

} 

- (void)removeInformation { 
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(removeDataWithOperation) object:nil]; 
    /* Add the operation to the queue */ 
    [queue addOperation:operation]; 
    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES]; 
} 

- (void) addDataWithOperation { 
    NSLog(@"Add data"); 
    [_arrInformations addObject:@"Informations"]; 
} 

- (void) removeDataWithOperation { 
    if (_arrInformations.count) { 
     [_arrInformations removeLastObject]; 
     [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES]; 
    } 
} 

Большое спасибо!

+0

который подходит, вы уже пробовали? – Vik

+0

вы ссылаетесь на мой код на приведенный выше –

ответ

0

Я не думаю, что вам нужно использовать NSOperationQueue для реализации этой функции. Grand Central Dispatch and Blocks должны предоставить вам необходимую функциональность.

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    _arrInformations = [[NSMutableArray alloc] init]; 
    _shouldContinue = YES; // set this to NO on viewWillDisappear to stop the dispatching 
    [self addNewInformation]; 
} 

-(void)addNewInformation { 
    [_arrInformations addObject:@"Informations"]; 
    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]; 
if (_shouldContinue) 
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 
      [self removeInformation]; 
     }); 
} 

- (void)removeInformation { 
    [_arrInformations removeObject:@"Informations"]; 
    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]; 
if (_shouldContinue) 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 
      [self addInformation]; 
     }); 
} 

Следует отметить, что вызов -reloadData каждые 10-15 мс будет иметь ОЧЕНЬ неприхотлива производительность IOS. Вы должны посмотреть на NSNotificationCenter и KVO в качестве альтернативных методов , отвечая на изменения данных, вместо того, чтобы приводить их в такой цикл.

0

Действительно, я бы не стал использовать NSOperationQueue либо, а просто пару NSTimer с:

NSTimer *producer = [NSTimer timerWithTimeInterval:0.001 target:self selector:@selector(produce:) userInfo:nil repeats:YES]; 
NSTimer *consumer = [NSTimer timerWithTimeInterval:0.001 target:self selector:@selector(consume:) userInfo:nil repeats:YES]; 

[[NSRunLoop mainRunLoop] addTimer:producer forMode:NSRunLoopCommonModes]; 
[[NSRunLoop mainRunLoop] addTimer:consumer forMode:NSRunLoopCommonModes]; 

А потом где-то в коде:

- (void) produce:(id)sender 
{ 
    //Produce your stuff here 
} 

- (void) consume:(id)sender 
{ 
    //Consume your stuff here 
} 

Или еще короче форма:

NSTimer *producer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(produce:) userInfo:nil repeats:YES]; 
NSTimer *consumer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(consume:) userInfo:nil repeats:YES]; 

Я назначаю таймеры переменным, так как в какой-то момент я предполагаю, что вы uld, чтобы остановить таймер, который вы делаете, отправив сообщение invalidate экземпляру.

Смежные вопросы