2013-02-14 70 views
1

我正在制作一个OX Cocoa应用程序,我希望能够使用按钮按下应用程序来读写文本文件。这些文本文件应该保存在/ Library/Application Support/AppName中,但是我无法让我的应用程序从那里读取任何内容。它可以写入文件夹,但不会读取它写入的内容,即使我可以在查找器中看到文件。如何从/库/应用程序支持/文件夹中读取?

这里是我使用的成功写入到该文件夹​​中的代码。

NSString *text = editor.string; 
    NSString *path = @"/Library/Application Support/"; 

    NSMutableString *mu = [[NSMutableString stringWithString:path] init]; 
    [mu insertString:FileName.stringValue atIndex:mu.length]; 
    [mu insertString:@".txt" atIndex:mu.length]; 

    path = [mu copy]; 
    [text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL]; 

这是我使用(和失败)从文本文件中读取的代码。

NSArray *path = [[NSBundle mainBundle] pathsForResourcesOfType:@"txt" inDirectory:@"/Library/Application Support/"]; 
    NSString *output = @""; 

    NSMutableString *mu = [[NSMutableString stringWithString:output] init]; 

    for (int i = 0; i < [path count]; i++) { 
     NSString *text = [NSString stringWithContentsOfFile:path[i] encoding:NSUTF8StringEncoding error:NULL]; 
     [mu insertString:text atIndex:mu.length]; 
     [mu insertString:@"\n" atIndex:mu.length]; 
    } 

    [textView setString:mu]; 

我能纠正的任何提示都会超级有用,我有点卡在这里。

编辑:使用您输入我已经更新了我的代码如下:

NSString *fileLocation = @"~/Library/Application Support/"; 
    NSArray *text = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fileLocation error:nil]; 
    NSString *output = @""; 
    NSMutableString *mu = [[NSMutableString stringWithString:output] init]; 

    for (int i = 0; i < [text count]; i++) { 
     [mu insertString:text[i] atIndex:mu.length]; 
     [mu insertString:@"\n" atIndex:mu.length]; 
    } 
    [textView setString:mu]; 

但是从文件的文本仍然没有出现。

回答

0

/库/应用程序支持是不是在你的包。您使用[[NSBundle mainBundle] pathsForResourcesOfType:…]获得的路径仅用于访问应用程序本身内的文件(图像,声音等,您在构建应用程序时包含的内容)。

你想用[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:error]让您的应用程序之外的目录中的文件列表。

马特·加拉格尔具有Cocoa With Love定位路径到您的应用程序支持目录的容错方法的一个很好的例子。我建议使用它来硬编码/ Library/Application Support路径。

NSError *error = nil; 
NSArray *text = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fileLocation error:&error]; 
if (!text) { 
    NSLog(@"Error reading contents of application support folder at %@.\n%@", applicationSupportFolder, [error userInfo]); 
} 
+0

在您的原始代码中编写您指向/ Library/Application Support的文件。你有没有改变它以匹配你在这里使用的〜/ Library/Application Support? – 2013-02-14 22:07:30

+0

是否有所作为? – 2013-02-14 22:09:01

+1

是的。 〜扩展为/ Users/*用户名*/Library/Application Support,不带〜进入全局/库/应用程序支持文件夹。 – 2013-02-14 22:09:52

0

你试图从应用程序的主包中获取使用NSBundle的路径。但该文件不在包中,您应该手动指定路径。您可以对路径进行硬编码,将以前写入的路径存储在某处,或使用NSFileManager获取目录内容并对其进行分析。例如,-[NSFileManager contentsOfDirectoryAtPath:error:]。当你Sandbox中的应用

1

大多数硬编码路径将失败。即使你逃避了这个,或者你不打算沙盒这个应用程序,这是一个值得离开的坏习惯。

而且,你确定你想/Library而不是~/Library?前者通常不能被用户写入。后者位于用户的主目录中(或沙盒时的容器)。

获取应用程序支持目录或Caches目录或任何其他目录,您可能想要创建它们并稍后从ask a file manager for it中检索它们。

相关问题