0
我有以下代碼來模擬我實驗室中的過程流程。由此計時器將新項目添加到NSMutablearray。我如何獲得while [數組數]!= 0循環來識別新增加的內容?將項目添加到NSMutableArray之後「重新啓動」循環
還是有更好的方法嗎?
我正在使用GCD塊來模擬並行進程。 HEFTBooker對象只需要一個樣本編號,然後在「標記」本身可以自由處理另一個樣本之前等待定義的時間段。
-(void)runBookingIn:(id)sender {
HEFTLaboratoryUnit *__labUnit = [[HEFTLaboratoryUnit alloc]init];
self.labUnit = __labUnit;
NSMutableArray *sampleNumbers = [[NSMutableArray alloc]init];
// Speed factor speeds up time for modelling i.e. 10 = 10 x normal time.
NSInteger speedFactor = 10;
// Sample arrival rate into laboratory per hour
NSInteger sampleArrivalRate = 50;
__weak id weakSelf = self;
self.timer = [RNTimer repeatingTimerWithTimeInterval:sampleArrivalRate/speedFactor block:^{
[weakSelf addNewSamplesToQueue];
}];
for (int i = 1; i <= 10; i++) {
[sampleNumbers addObject:[NSNumber numberWithInteger:i]];
}
self.labUnit.samplesToBeBookedIn = sampleNumbers;
NSMutableArray *bookerIns = [[NSMutableArray alloc]init];
HEFTBookerIn *webster = [[HEFTBookerIn alloc]init];
webster.bookingInRate = 60;
[email protected]"Webster";
[bookerIns addObject:webster];
HEFTBookerIn *duffy = [[HEFTBookerIn alloc]init];
duffy.bookingInRate = 30;
[email protected]"Duffy";
[bookerIns addObject:duffy];
HEFTBookerIn *marrington = [[HEFTBookerIn alloc]init];
marrington.bookingInRate = 40;
[email protected]"Marrington";
[bookerIns addObject:marrington];
HEFTBookerIn *chatha = [[HEFTBookerIn alloc]init];
chatha.bookingInRate = 10;
[email protected]"Kam";
[bookerIns addObject:chatha];
int i = 0;
long countSamples;
countSamples = [self.labUnit.samplesToBeBookedIn count];
// loop sample numbers
dispatch_queue_t queue;
queue = dispatch_queue_create("com.HEFT.BookerQueue", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t arrivalsQueue;
arrivalsQueue = dispatch_queue_create("com.HEFT.ArrivalsQueue", DISPATCH_QUEUE_SERIAL);
while ([self.labUnit.samplesToBeBookedIn count] != 0)
{
NSInteger sampleNo = [[self.labUnit.samplesToBeBookedIn objectAtIndex:i] integerValue];
long count = [bookerIns count];
int counter = 0;
//loop over booker ins
int j;
for (j=0; j <count ; j++) {
HEFTBookerIn *booker = [bookerIns objectAtIndex:counter];
if (booker.free == YES){
dispatch_sync(queue, ^{
[booker bookingIn:sampleNo :speedFactor];
[self.labUnit.samplesToBeBookedIn removeObjectAtIndex:i];
});
break;
}
else{
counter ++;
}
}
}
}
-(void) addNewSamplesToQueue{
NSLog(@"More Samples Arriving");
for (int i = 1; i <= 10; i++) {
[self.labUnit.samplesToBeBookedIn addObject:[NSNumber numberWithInteger:i]];
}
}
注意[NSMutableArray的不是線程安全的(http://developer.apple.com/library/mac /#documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html) – Sebastian 2013-03-21 22:27:40
並且雙下劃線保留爲compil呃關鍵字。 – CodaFi 2013-03-22 00:11:20
謝謝,所以我想我必須想出一個不同的方法 – 2013-03-22 12:04:23