IOS如何检查我是否完成循环?

标签 ios objective-c if-statement for-loop nsxmlparser

我有一个正确循环的 for 循环。但是我想检查循环是否已经完成循环,如果是我想执行一个 Action 如果没有我想执行另一个 Action 。

这里是代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    [loadingview setHidden:NO];
    NSLog(@"Response recieved");

    output = [[NSMutableArray alloc] init];
    feeds = [[NSMutableArray alloc] init];
    deepsightSig = [[NSArray alloc] init];
    lastEl = [item_pass lastObject];

    for (int i = 0; i < item_pass.count; i++) {
      NSString *soapMessage = //soap message
      url = [NSURL URLWithString:@"https://abc/SWS/hellworld.asmx"];
      theRequest = [NSMutableURLRequest requestWithURL:url];
      msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soapMessage length]];

      [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
      [theRequest addValue: @"https://www.hello.com/helloworld" forHTTPHeaderField:@"SOAPAction"];
      [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
      [theRequest setHTTPMethod:@"POST"];
      [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

      connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
      [connection start];
      if (i == item_pass.count - 1) {
        // this is the end of the loop
      }
    }
}

最佳答案

好的,让我们一起分解一下。首先我们仔细看看 for循环:

for (int i = 0; i < 5; i++) {
}

括号内分为三部分。

  1. int i = 0 : 即使没有阅读文档或任何有关编程的书籍,这看起来也像是循环变量的初始设置 i .
  2. i < 5 : 这看起来像是某种条件。循环变量 i应该小于 5。这可能意味着当循环变量变得大于或等于 5 时循环结束。
  3. i++ : 呃,这很奇怪。但是当我们用等价的表达式替换它时,它会变得更加清晰。 i++等同于 i = i + 1 .现在很明显,这是在每个循环之后但结束条件 (i < 5) 被评估之前执行的语句。

好吧,让我们假设我们仍然没有真正理解循环是什么以及它做了什么。为了更好地理解,我们可以在循环中添加一个断点,让调试器帮助我们理解它。或者我们可以添加一条日志语句:

for (int i = 0; i < 5; i++) {
    NSLog(@"i: %d", i);
}

这会产生输出:

i: 0
i: 1
i: 2
i: 3
i: 4

它告诉我们可以从循环内访问循环变量。不要让我们将循环中的代码更改为仅在第一次和最后一次迭代期间记录日志:

for (int i = 0; i < 5; i++) {
    if (i == 0) {
        NSLog(@"This might be the first iteration: i = %d", i);
    } else if (i == 5 - 1) {
        NSLog(@"This might be the last iteration: i = %d", i);
    }
}

输出看起来像这样:

This might be the first iteration: i = 0
This might be the last iteration: i = 4

我希望这能回答您的问题。

关于IOS如何检查我是否完成循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33865833/

相关文章:

ios - 获取 block 的弱类型的宏

ios - 如何限制文本字段只能输入十进制数字?

objective-c - 使用音频队列服务录制 aac 时保存到缓冲区而不是文件

R: ifelse 把 numeric(0) 变成 NA

vb.net - ASP.NET MVC3 - VB 中的 If 语句

ios - 向图层添加阴影

ios - 带路线的离线 map - iOS

ios - 如何使用 ViewController 中的不同对象在每台 iPhone 和 iPad 上全屏显示?

ios - 为 UIImagePickerController 选择视频时崩溃

php - 如何在 SQL 查询中动态累积复选框值