将目录中的所有图像添加到MWPhotoBrowser的更简单方法?

时间:2013-08-11 15:22:06

标签: ios arrays nsmutablearray mwphotobrowser

我对目标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语句”。如果他们超出界限就会导致崩溃。任何人都可以提供我需要的工作示例。一个解释将不胜感激。感谢

1 个答案:

答案 0 :(得分: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];
}

BTW - 此代码仅在模拟器中有效,因为您正在对库路径进行硬编码。

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