Retired Document
Important: This document describes behavior on old releases of OS X and no longer represents best practices for OS X v10.8 and later or iOS 6 and later.
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.
Declare the
applicationLogDirectory()
function.In the main source file, before
main()
declare a function,applicationLogDirectory()
, that returns anNSURL
object:NSURL *applicationLogDirectory();
After
main()
, implement theapplicationLogDirectory()
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;
}
Update the main function to invoke the
applicationLogDirectory()
function.In the
main
function, after the invocation of themanagedObjectModel
function, invokeapplicationLogDirectory()
; if it returnsnil
, 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.
Copyright © 2005, 2013 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2013-09-18