+ (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都已发布。
可变释放还是不释放?请给我建议。
答案 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]; ?
您需要同时发布today
和dateFormatter
,因为您alloc
已对其进行了编辑。始终在您自己的代码中将alloc
与release
或autorelease
配对。
答案 1 :(得分:1)