Objective C - NSArray和For循环结构

Pau*_*ers 5 iphone for-loop objective-c nsarray

工作妨碍了学习目标C,但我现在又回到了它,这让我发疯了.

这是我的代码:

i=0;
    for (i=0;[photoList count]; i++) {
        NSLog(@"%i",i);
        NSLog(@"%@",[photoList objectAtIndex:i]);
        NSString *fileName = [photoList objectAtIndex:i];
        sendImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:nil]];
        UIImageWriteToSavedPhotosAlbum(sendImage,self,@selector(savedPhotoImage:didFinishSavingWithError:contextInfo:),NULL);}
Run Code Online (Sandbox Code Playgroud)

photoList只是一个NSArray,只有24个对象:

NSArray* photoList = [NSArray arrayWithObjects:@"Photo 1.jpg",
    @"Photo 2.jpg",
    @"Photo 3.jpg",
    @"Photo 4.jpg",nil];
Run Code Online (Sandbox Code Playgroud)

它有效...它将照片复制到相机胶卷......然后崩溃

2010-07-24 19:34:36.116 iCardz2go Poindexter [29662:207] *由于未捕获的异常'NSRangeException'终止应用程序,原因:'* - [NSArray objectAtIndex:]:索引24超出边界[0 .. 23]'

我尝试了各种配置,比如

for (i=0;1<23; i++)
Run Code Online (Sandbox Code Playgroud)

只能得到2010-07-24 19:51:01.017 iCardz2go Poindexter [29908:207]***由于未捕获的异常'NSInvalidArgumentException'终止app,原因:'+ [NSInvocation invocationWithMethodSignature:]:方法签名参数不能为nil'

所以它正在读取零并传递它.

我知道它会变得非常简单,我已经忘记了.为什么不跳出照片23(计数)的循环?

非常感谢您的帮助!P

Eim*_*tas 19

你为什么不尝试快速枚举?

for (NSString *photoFile in photoList) {
  NSLog(@"%@", photoFile);
  sendImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] 
                               pathForResource:photoFile 
                                        ofType:nil]];

  UIImageWriteToSavedPhotosAlbum(sendImage, self, @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), NULL);}
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*pan 12

对于C和Objective-C中的循环,如下所示:

for (initialization; condition; increment) {
    // body
}
Run Code Online (Sandbox Code Playgroud)

initialization是你设置循环的地方; 它是你告诉它从哪里开始的地方.condition测试每次迭代,包括第一次; 如果condition计算结果为true,则执行循环体.在每次迭代结束时,increment进行评估.

所以:

for (int i = 0; i < 10; i++) {
    printf("%i\n", i);
}
Run Code Online (Sandbox Code Playgroud)

将打印数字0到9.您可能想要的是:

NSUInteger count = [photoList count];
for (NSUInteger i = 0; i < count; i++) {
    NSString *fileName = [photoList objectAtIndex: i];
    sendImage = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource: fileName ofType: nil]];
    UIImageWriteToSavedPhotosAlbum(sendImage, self, @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), NULL);
}
Run Code Online (Sandbox Code Playgroud)

注意count循环外的分配; 它只是一个优化,所以循环不必为每次迭代发送额外的消息(你可以这样做)i < [photoList count].

这有帮助吗?