Mac OS X Reference Library Apple Developer
Search

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

This section illustrates a simple means 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.

In the main source file, before main() declare a function, applicationLogDirectory(), that returns an NSURL object, then after main() implement it as follows:

NSURL *applicationLogDirectory() {
    NSString *LOG_DIRECTORY = @"CDCLI";
    static NSURL *ald = nil;
 
    if (ald == nil) {
 
        NSFileManager *fileManager = [[NSFileManager alloc] init];
        NSError *error = nil;
        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:
                                        [NSArray arrayWithObject:NSURLIsDirectoryKey] error:&error];
            if (properties == nil) {
                if (![fileManager createDirectoryAtPath:[ald path]
                                  withIntermediateDirectories:YES attributes:nil error:&error]) {
                    NSLog(@"Could not create directory %@\n%@",
                            [ald path], [error localizedDescription]);
                    ald = nil;
                }
            }
        }
    }
    return ald;
}

Update the main 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.




Last updated: 2010-05-24

Did this document help you? Yes It's good, but... Not helpful...