Добавление NSString при использовании NSApplicationSupportDirectory для создания нового каталога - PullRequest
1 голос
/ 12 февраля 2011

Я пытался создать новый файл в моей папке поддержки приложений при использовании NSApplicationSupportDirectory;Я могу записать в него файл, но мне не удалось создать папку внутри службы поддержки приложений.

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationDirectory =  [paths objectAtIndex:0];  

//make a file name to write the data to using the application support: (attempting to create the blasted directory inside of application support directory
NSString *fileName = [NSString stringWithFormat:@"%@/managersemail.txt",
                      applicationDirectory];
//create content - formats with the managersemail.txt location
NSString* content = [NSString stringWithFormat:@"%@",[nameField stringValue]];
//save content to the documents directory
[content writeToFile:fileName
          atomically:NO
            encoding:NSStringEncodingConversionAllowLossy
               error:nil];


NSDictionary* errorDict;

Код, который я перечислил выше, прекрасно работает, за исключением части о создании папки, в которую я хочу поместить managersemail.txt.Я попытался имитировать строку stringWithFormat, которая указана в содержимом NSString *, и затем менял ее несколькими способами, но безрезультатно!Есть мысли?

NSAppleEventDescriptor* returnDescriptor = NULL;

Ответы [ 2 ]

3 голосов
/ 12 февраля 2011

Может быть, может пригодиться решение , предоставленное на Какао с любовью?

Выдержка:

- (NSString *)findOrCreateDirectory:(NSSearchPathDirectory)searchPathDirectory
    inDomain:(NSSearchPathDomainMask)domainMask
    appendPathComponent:(NSString *)appendComponent
    error:(NSError **)errorOut
{
    // Search for the path
    NSArray* paths = NSSearchPathForDirectoriesInDomains(
        searchPathDirectory,
        domainMask,
        YES);
    if ([paths count] == 0)
    {
        // *** creation and return of error object omitted for space
        return nil;
    }

    // Normally only need the first path
    NSString *resolvedPath = [paths objectAtIndex:0];

    if (appendComponent)
    {
        resolvedPath = [resolvedPath
            stringByAppendingPathComponent:appendComponent];
    }

    // Check if the path exists
    BOOL exists;
    BOOL isDirectory;
    exists = [self
        fileExistsAtPath:resolvedPath
        isDirectory:&isDirectory];
    if (!exists || !isDirectory)
    {
        if (exists)
        {
            // *** creation and return of error object omitted for space
            return nil;
        }

        // Create the path if it doesn't exist
        NSError *error;
        BOOL success = [self
            createDirectoryAtPath:resolvedPath
            withIntermediateDirectories:YES
            attributes:nil
            error:&error];
        if (!success) 
        {
            if (errorOut)
            {
                *errorOut = error;
            }
            return nil;
        }
    }

    if (errorOut)
    {
        *errorOut = nil;
    }
    return resolvedPath;
}
1 голос
/ 12 февраля 2011

Возможно, вы можете попробовать использовать NSFileManager для создания папки, а затем записать файл в папку.

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *applicationSupport = [[NSString stringWithString:@"~/Library/Application Support/'YOUR APP'] stringByExpandingTildeInPath];
if ([fileManager fileExistsAtPath:applicationSupport] == NO)
    [fileManager createDirectoryAtPath:applicationSupport withIntermediateDirectories:YES attributes:nil error:nil];

NSString *fileName = [NSString stringWithFormat:@"%@/managersemail.txt", applicationSupport];
NSString* content = [NSString stringWithFormat:@"%@",[nameField stringValue]];
//save content to the documents directory
[content writeToFile:fileName
          atomically:NO
            encoding:NSStringEncodingConversionAllowLossy
               error:nil];

Так что-то подобное должно работать. Не стесняйтесь оставлять комментарии, чтобы задавать вопросы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...