The Application Log Directory

The utility needs somewhere to save the file for the persistent store. This section illustrates one way to identify and if necessary create an appropriate directory. Although it is a useful abstraction for the utility, this is not directly relevant to Core Data, so no additional explanation is given. For details about locating system directories, see Low-Level File Management Programming Topics.

The applicationLogDirectory Function

Implement a function to identify and if necessary create a directory (in ~/Library/Logs—the Logs directory in your home directory) in which to save the file for the persistent store.

bullet
To implement and use the applicationLogDirectory function
  1. Declare the applicationLogDirectory() function.

    In the main source file, before main() declare a function, applicationLogDirectory(), that returns an NSURL object:

    NSURL *applicationLogDirectory();
  2. After main(), implement the applicationLogDirectory() function.

    Implement the applicationLogDirectory() function as follows:

    NSURL *applicationLogDirectory() {
     
        NSString *LOG_DIRECTORY = @"CDCLI";
        static NSURL *ald = nil;
     
        if (ald == nil) {
     
            NSFileManager *fileManager = [[NSFileManager alloc] init];
            NSError *error;
            NSURL *libraryURL = [fileManager URLForDirectory:NSLibraryDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error];
            if (libraryURL == nil) {
                NSLog(@"Could not access Library directory\n%@", [error localizedDescription]);
            }
            else {
                ald = [libraryURL URLByAppendingPathComponent:@"Logs"];
                ald = [ald URLByAppendingPathComponent:LOG_DIRECTORY];
                NSDictionary *properties = [ald resourceValuesForKeys:@[NSURLIsDirectoryKey]
                                                                error:&error];
                if (properties == nil) {
                    if (![fileManager createDirectoryAtURL:ald withIntermediateDirectories:YES attributes:nil error:&error]) {
                        NSLog(@"Could not create directory %@\n%@", [ald path], [error localizedDescription]);
                        ald = nil;
                    }
                }
            }
        }
        return ald;
    }
  3. Update the main function to invoke the applicationLogDirectory() function.

    In the main function, after the invocation of the managedObjectModel function, invoke applicationLogDirectory(); if it returns nil, exit.

    if (applicationLogDirectory() == nil) {
        exit(1);
    }

Build and Test

Build and run the utility. It should compile without warnings. The application log directory should be created correctly, and no errors should be logged.