【问题标题】:Manual VS Automatic Array Clarification手动 VS 自动阵列澄清
【发布时间】:2014-10-05 22:22:02
【问题描述】:

在我的应用程序中,我将从手动创建对象数组转变为创建对象存储在引用文件夹中的相等数组。我用 contentsOfDirectoryAtPath 创建了自动数组。

问题是当我稍后在我的集合视图 cellForItemAtIndexPath 中引用该数组时。手动创建的数组运行良好,但自动数组的格式不同并引发错误。

区别在于手动创建的数组有 3 个对象,而自动创建的数组只有一个对象,在日志中以额外的一组括号显示。如何让自动创建的数组单独添加每个文件夹对象,这样我就可以获得一个包含 3 个对象的数组,就像我使用手动创建的数组一样?提前感谢您的宝贵时间。

手动创建targetArray

//@interface

@property (nonatomic, strong) NSArray *targetArray;

//viewdidLoad   

self.targetArray = @[@"one",@"two", @"three"];

NSLog(@"Target Array description test = %@", [_targetArray description]);

//returns

Target Array description test = (
"one",
"two",
"three"
 )

通过读取参考文件夹自动创建数组

//@interface

@property (nonatomic, strong) NSArray *targetArray;

//viewdidLoad

for (int i = 0; i <= [folderArray count] -1; i++) {

NSString *sectionString = [folderArray objectAtIndex:i];

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

NSArray *targetArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:nil];

NSLog(@"Target Array description test = %@", [_targetArray description]);

}

//returns

Target Array description test = (
    (
    "one",
    "two",
    "three"
  )
 )

cellForRowAtIndexPath for w/Error log for reference

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

sheetCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SheetCell" forIndexPath:indexPath];

NSLog(@"Target Array description test = %@", [_targetArray description]);

NSString *sheetString = [self.targetArray objectAtIndex:indexPath.row];

ERROR: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM stringByDeletingPathExtension]: unrecognized selector sent to instance 0x78794450'

cell.sheetImageView.image = [UIImage imageNamed:sheetString];

cell.sheetLabel.text = sheetString;

return cell;

}

【问题讨论】:

  • 您似乎有两个不同的对象,名为 targetArray:一个是 self.targetArray(也可以通过其实例变量 _targetArray 访问),另一个是您在 for 循环中声明的(NSArray *targetArray)。您的 NSLogs 仅指前者。你的 for 循环也没有结束 } - 这是一个错字吗?

标签: ios objective-c arrays nsarray nsfilemanager


【解决方案1】:

如果您知道“contentsOfDirectoryAtPath”方法将始终返回一个包含单个元素外部数组的对象数组,您可以通过以下方式“解包”内部数组:

NSArray *targetArray = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:nil] objectAtIndex:0];

(我不在我的电脑上通过 XCode 运行上面的代码来检查它是否编译)

附带说明一下,您提供的代码 sn-ps 存在一些问题(可能是拼写错误或复制/粘贴错误),因为您正在分配一个名为“targetArray”的局部变量,然后访问一个实例变量在打印语句中称为“targetArray” - 不是相同的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-11
    • 2016-12-27
    • 2018-11-15
    • 2016-11-08
    • 2012-06-14
    • 2012-07-20
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多