变量不为零后退出循环

Escape loop after variable not nil

我希望我的条形码扫描应用程序在找到结果后停止扫描。这是我的代码:

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:        (AVCaptureConnection *)connection
{
CGRect highlightViewRect = CGRectZero;
AVMetadataMachineReadableCodeObject *barCodeObject;
NSString *detectionString = nil;
NSArray *barCodeTypes = @[AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code,
        AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code,
        AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode];

for (AVMetadataObject *metadata in metadataObjects) {
    for (NSString *type in barCodeTypes) {
        if ([metadata.type isEqualToString:type])
        {
            barCodeObject = (AVMetadataMachineReadableCodeObject *)[_prevLayer transformedMetadataObjectForMetadataObject:(AVMetadataMachineReadableCodeObject *)metadata];
            highlightViewRect = barCodeObject.bounds;
            detectionString = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
            break;
        }
    }

    if (detectionString != nil)
    {

        NSString *connect = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", @"http://example.com/index.php?b=", detectionString]] encoding:NSUTF8StringEncoding error:nil];

        _label.text = connect;

        break;
    }
    else
        _label.text = @"Scan Barcode";
}

_highlightView.frame = highlightViewRect;

}

我基本上想通过 NSURL 将条形码发送到我的服务器,如下所示。尽管目前它一直在发送多个请求。我只希望它发送一次 NSURL 然后停止。

你应该将 NSString *detectionString = nil; 移到函数之外,这样它就不会在每次调用该方法时都被重置,并且如果你设置了 detectionString,请在 for 循环之前进行检查以使其不会进入它已经

所以把你的 detectionString 变量放在你的函数之外。否则,每次调用该函数时,都会一次又一次地声明 detectionString。

@interface YourClassName ()
@property (strong, nonatomic) NSString *detectionString;
@end

- (void)viewDidLoad{
   self.detectionString = nil;
}