0

我对目标 c 的了解有限,我找到了一种方法来做我需要的事情。我只是认为它根本没有效率。

我正在尝试将应用程序包外部目录中的所有图像添加到 MWPhotoBrowser。问题是,他们不会有特定的前任名称。2f5h3h5y.png。

NSMutableArray *photos = [[NSMutableArray alloc] init];

NSMutableArray *myArray = [[NSMutableArray alloc] init];
NSString *filePath = @"/Library/Application Support/Testing/Testing";
NSString *absolutePath;



MWPhoto *photo;
switch (indexPath.row) {
    case 0:

        myArray = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:NULL] mutableCopy];

        NSLog(@"~~~~~~~~~~~~MY ARRAY COUNT: %d", [myArray count]);

        if ([myArray count] == 1){

            absolutePath = [NSString stringWithFormat:@"%@/%@", filePath, [myArray objectAtIndex:0]];

            photo = [MWPhoto photoWithFilePath:absolutePath];
            [photos addObject:photo];

        } else if ([myArray count] == 2){

            absolutePath = [NSString stringWithFormat:@"%@/%@", filePath, [myArray objectAtIndex:0]];

            photo = [MWPhoto photoWithFilePath:absolutePath]; 
            [photos addObject:photo];

            absolutePath = [NSString stringWithFormat:@"%@/%@", filePath, [myArray objectAtIndex:1]];

            photo = [MWPhoto photoWithFilePath:absolutePath];
            [photos addObject:photo];

        } else if ([myArray count] == 3){

            absolutePath = [NSString stringWithFormat:@"%@/%@", filePath, [myArray objectAtIndex:0]];

            photo = [MWPhoto photoWithFilePath:absolutePath];
            [photos addObject:photo];

            absolutePath = [NSString stringWithFormat:@"%@/%@", filePath, [myArray objectAtIndex:1]];

            photo = [MWPhoto photoWithFilePath:absolutePath];
            [photos addObject:photo];

            absolutePath = [NSString stringWithFormat:@"%@/%@", filePath, [myArray objectAtIndex:1]];

            photo = [MWPhoto photoWithFilePath:absolutePath];
            [photos addObject:photo];

        }

我知道这种方法行不通,因为我无法设置 1000 个“if 语句”。如果它们超出范围,将导致崩溃。谁能提供我需要的工作示例。解释将不胜感激。谢谢

4

1 回答 1

1

您需要了解循环。

NSMutableArray *photos = [[NSMutableArray alloc] init];
NSString *filePath = @"/Library/Application Support/Testing/Testing";
NSArray *myArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:nil];
for (NSString *filename in myArray) {
    NSString *fullPath = [filePath stringByAppendingPathComponent:filename];
    MWPhoto *photo = [MWPhoto photoWithFilePath:fullPath];
    [photos addObject:photo];
}

顺便说一句 - 由于您对库路径进行硬编码,因此此代码仅适用于模拟器。

此代码还假定目录中的唯一文件是图像文件。

于 2013-08-11T16:05:47.717 回答