Mac OS X Reference Library Apple Developer Connection spyglass button

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.

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 NSString object, then implement it as follows:

NSString *applicationLogDirectory() {
    NSString *LOG_DIRECTORY = @"CDCLI";
    static NSString *ald = nil;
 
    if (ald == nil) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains
                (NSLibraryDirectory, NSUserDomainMask, YES);
        if ([paths count] == 1) {
            ald = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Logs"];
            ald = [ald stringByAppendingPathComponent:LOG_DIRECTORY];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            BOOL isDirectory = NO;
            if (![fileManager fileExistsAtPath:ald isDirectory:&isDirectory]) {
                if (![fileManager createDirectoryAtPath:ald attributes:nil]) {
                    ald = nil;
                }
            }
            else {
                if (!isDirectory) {
                    ald = nil;
                }
            }
        }
    }
    return ald;
}

Update the main Function

In the main function, after the invocation of the managedObjectModel function, invoke applicationLogDirectory(), and ensure that it does not return nil. If it does, report an error and exit.

if (applicationLogDirectory() == nil) {
    NSLog(@"Could not find application log directory\nExiting...");
    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: 2009-03-04

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