手动VS自动阵列澄清

时间:2014-10-05 22:22:03

标签: ios objective-c arrays nsarray nsfilemanager

在我的应用程序中,我将手动创建一个对象数组,创建一个相等的数组,其中对象存储在参考文件夹中。我使用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;

}

1 个答案:

答案 0 :(得分:0)

如果您知道&#34; contentsOfDirectoryAtPath&#34;方法将始终返回一个对象数组,在单个元素外部数组中,你可以&#34; unpackage&#34;内部数组:

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

(我不是在我的电脑上通过XCode运行以上程序来检查它是否编译)

作为旁注,您提供的代码片段存在一些问题(可能是错别字或复制/粘贴错误),因为您要分配一个名为&#34; targetArray&#34;的局部变量。然后访问名为&#34; targetArray&#34;的实例变量在print语句中 - 不是相同的对象。

相关问题