【问题标题】:Array of NSStrings from filenames within a folder?来自文件夹中文件名的 NSString 数组?
【发布时间】:2010-08-03 19:45:10
【问题描述】:

我正在尝试创建一个包含已拖入项目的文件夹内容的 NSStrings 数组...但是当我之后计算数组中的项目时,它总是返回 0;

所以,我的项目中的文件夹是这样的

-Cards
  -Colors
     Blue.png
     Green.png
     Orange.png
     Yellow.png
     Purple.png
     Black.png

而我试图获取此文件列表(颜色 png)的代码是

NSError *error = nil;
NSString *pathString = [[NSString alloc] init];
pathString = [[NSString alloc] initWithString:@"/Cards/Colors/"];
NSArray *fileList = [[NSArray alloc] init];
fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathString error: &error];
[pathString release];
NSLog(@"%@", error);
// this is always 0
NSLog(@"file list has %i items", [fileList count]);

我得到的 NSError 是

Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x596db00 {NSUserStringVariant=(
    Folder
), NSFilePath=/Cards/Color/, NSUnderlyingError=0x5925ef0 "The operation couldn’t be completed. No such file or directory"}

任何想法我哪里出错了?

【问题讨论】:

    标签: iphone objective-c nsfilemanager


    【解决方案1】:

    您正在将pathString 初始化为绝对路径/Cards/Colors/。此路径是系统范围的路径,因此在 iPhone 上,远离您应用的沙箱。

    试试这个:

    NSString *pathString = [[NSBundle mainBundle] pathForResource:@"Cards/Colors" ofType:nil];
    NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathString error: &error];
    

    (请注意,您在问题中使用代码的方式是分配/初始化fileList,然后通过将contentsOfDirectoryAtPath:error: 的结果分配给它来立即泄漏对象。这是一个错误。)

    【讨论】:

    • 谢谢,pathString 在第一行之后是空的,因此我在下一行得到一个 '*** Terminating app due to uncaught exception 'NSInvalidArgumentException''。我想知道我是否正确添加了文件夹..?
    • 可能是这样。我认为 Xcode 组不会自动成为捆绑包中的目录。也可能是 pathForResource:ofType: 不适用于目录。在这种情况下,使用-[NSBundle bundlePath] 获取包根目录的路径,然后使用-[NSString stringByAppendingPathComponent:] 获取您的子目录。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多