I have a question about variable release in global class
+ (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.
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.
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
加载中,请稍侯......
精彩评论