views:

31

answers:

2
+ (void)findAndCopyOfDatabaseIfNeeded{
NSArray         *path               = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString        *documentsDirectory = [path objectAtIndex:0];

NSFileManager   *fileManager        = [NSFileManager defaultManager];
NSString        *databasePath       = [documentsDirectory stringByAppendingPathComponent:@"DB"];
BOOL success = [fileManager fileExistsAtPath:databasePath];
if(!success){
    NSString *resourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"DB"];
    [fileManager copyItemAtPath:resourcePath toPath:databasePath error:NULL];
}

NSString        *tracePath          = [documentsDirectory stringByAppendingPathComponent:@"Trace"];
BOOL traceDir = [fileManager fileExistsAtPath:tracePath];
if(!traceDir){
    NSString        *resourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Trace"];
    [fileManager copyItemAtPath:resourcePath toPath:tracePath error:NULL];
}


NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy"];

NSDate   *today         = [[NSDate alloc]init];
NSString *resultYear    = [dateFormatter stringFromDate:today];
NSString *traceYearPath = [tracePath stringByAppendingPathComponent:resultYear];
BOOL yearDir = [fileManager fileExistsAtPath:tracePath];
if (!yearDir) {
    [fileManager createDirectoryAtPath:traceYearPath attributes:nil];
}
//[resultYear     release];  ?
//[today      release];  ?
//[dateFormatter  release];  ?

}

I'm using global class like this [ + (void)findAndCopyOfDatabaseIfNeeded ]. hm,, I don't know NSArray, NSString and NSFileManager are released.

Variable release or Not release ? please advice for me.

+1  A: 
NSString *resultYear    = [dateFormatter stringFromDate:today];
//[resultYear     release];  ?

You do not need to release resultYear. The object returned from the stringFromDate: will be autorelease'd.

It's usually safe to assume that objects returned from methods whose names do not start with "create" or "new" will be autorelease'd. At least with Apple code, but this is a convention for Cocoa in general, so you should also follow it.

NSDate   *today         = [[NSDate alloc]init];
//[today      release];  ?
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
//[dateFormatter  release];  ?

You need to release both today and dateFormatter, since you alloc'ed them. Always pair an alloc with a release or autorelease in your own code.

Shaggy Frog
Thank you very much~!
Beomseok
+1  A: 

yes, and some more: do not release NSArray * path - it is autoreleased (almost always id returned by functions are).
also do not release fileManager - it is shared singleton object

Vladimir
Thank you very much~!
Beomseok