我对全局类中的变量发布有疑问

时间:2010-03-31 20:48:55

标签: iphone release global

+ (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];  ?

}

我正在使用这样的全局类[+(void)findAndCopyOfDatabaseIfNeeded]。 嗯,我不知道NSArray,NSString和NSFileManager都已发布。

可变释放还是不释放?请给我建议。

2 个答案:

答案 0 :(得分:1)

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

您无需release resultYear。从stringFromDate:返回的对象将为autorelease'd。

通常可以安全地假设从名称不以“create”或“new”开头的方法返回的对象将是autorelease'd。至少使用Apple代码,但这通常是Cocoa的惯例,所以你也应该遵循它。

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

您需要同时发布todaydateFormatter,因为您alloc已对其进行了编辑。始终在您自己的代码中将allocreleaseautorelease配对。

答案 1 :(得分:1)

是的,还有一些: 不要释放NSArray *路径 - 它是自动释放的(几乎总是由函数返回的id) 也不释放fileManager - 它是共享的单例对象