I have a question about variable release in global class - iphone

+ (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

Related

Compare NSFileModificationDate of previous Backup

Here am creating backup of my database. But i don want to jus keep creating backups. i need to check the NSModificationDate property of the most recently created backup database and have to create new backup only if the database is modified. Can anyone help me on this.
-(IBAction)createdb:(id)sender
{
DatabaseList = [[NSMutableArray alloc]init];
NSDate *currentDateTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMddyyyyHHmmss"];
NSString *dateInStringFormated = [dateFormatter stringFromDate:currentDateTime];
dbNameString = [NSString stringWithFormat:#"UW_%#.db",dateInStringFormated];
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolderPath = [searchPaths objectAtIndex: 0];
NSString *dbName = #"UnitWiseDB.db";
NSString *dbPath1 = [documentFolderPath stringByAppendingPathComponent:dbNameString];
NSString *backupDbPath = [documentFolderPath stringByAppendingPathComponent:dbName];
NSError *error = nil;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:backupDbPath error:&error];
NSLog(#"Persistent store size: %# bytes", [fileAttributes objectForKey:NSFileSize]);
NSLog(#"Modification Date: %# ",[fileAttributes objectForKey:NSFileModificationDate]);
if ( ![[NSFileManager defaultManager] fileExistsAtPath:dbPath1])
{
[[NSFileManager defaultManager] copyItemAtPath:backupDbPath toPath:dbPath1 error:nil];
}
NSLog(#"DBPath.......%#",dbPath1);
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager contentsOfDirectoryAtPath:documentFolderPath error:nil];
for (NSString *s in fileList)
{
NSLog(#"Backup.....%#", s);
[DatabaseList addObject:s];
}
[ListViewTableView reloadData];
}
Instead of checking modification , you can use a simple trick as described by trojanfoe.
When ever you are modifying i mean adding/ removing/ editing any record in database , set a BOOL flag = YES and store in NSUSERDEFAULTS , after creating the backup, set the flag to NO.

Creating folder and adding multiple images

I'm creating an iPhone app where I need to create separate folder and add images in those folder and upload that whole folder on google drive. How can i create folder and images to it.
Thanks in advance
Creating A Folder
NSString *pngPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:#"/WB/%#",self.viewIndex]];
// Check if the directory already exists
BOOL isDir;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:pngPath isDirectory:&isDir];
if (exists)
{
if (!isDir)
{
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:pngPath error:&error];
// Directory does not exist so create it
[[NSFileManager defaultManager] createDirectoryAtPath:pngPath withIntermediateDirectories:YES attributes:nil error:nil];
}
}
else
{
// Directory does not exist so create it
[[NSFileManager defaultManager] createDirectoryAtPath:pngPath withIntermediateDirectories:YES attributes:nil error:nil];
}
Adding Images to that Folder
NSString *pngImagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:#"/WB/%#/%d.png",self.viewIndex,lineIndex]];
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 1.0);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
self.curImage = UIGraphicsGetImageFromCurrentImageContext();
[UIImagePNGRepresentation(self.curImage) writeToFile:pngImagePath atomically:YES];
UIGraphicsEndImageContext();
Try this :
//For save to Document Directory
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH:mm:ss"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
NSString *strImageName=[NSString stringWithFormat:#"Documents/MyPhotos/Dt%#%#.png",theDate,theTime];
strImageName=[strImageName stringByReplacingOccurrencesOfString:#"-" withString:#""];
strImageName=[strImageName stringByReplacingOccurrencesOfString:#":" withString:#""];
[self createDocumentDirectory:#"MyPhotos"];
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:strImageName];
[UIImagePNGRepresentation(YourImageView.image) writeToFile:pngPath atomically:YES];
-(void)createDocumentDirectory:(NSString*)pStrDirectoryName
{
NSString *dataPath = [self getDocumentDirectoryPath:pStrDirectoryName];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:NULL];
}
-(NSString*)getDocumentDirectoryPath:(NSString*)pStrPathName
{
NSString *strPath = #"";
if(pStrPathName)
strPath = [[kAppDirectoryPath objectAtIndex:0] stringByAppendingPathComponent:pStrPathName];
return strPath;
}
//Get Photo Onebyone
NSError *error = nil;
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self getDocumentDirectoryPath:#"MyPhotos"] error:&error];
if (!error) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self ENDSWITH '.png'"];
NSArray *imagesOnly = [dirContents filteredArrayUsingPredicate:predicate];
for (int i=0;i<[imagesOnly count]; i++) {
[arrSaveImage addObject:[imagesOnly objectAtIndex:i]];//Save in your array.
}
}

Get document directory files date modified time in iphone

NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *currDircetory = [documentPath objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:currDircetory error:nil];
for (NSString *s in filePathsArray){
NSLog(#"file %#", s);
}
Now i used the above code to get list of file from document directory now i want to know how to get modified time of the file in document directory.
Thanks,
Vijayan
You can use this :
NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *currDircetory = [documentPath objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:currDircetory error:nil];
for (NSString *s in filePathsArray){
NSString *filestring = [currDircetory stringByAppendingFormat:#"/%#",s];
NSDictionary *filePathsArray1 = [[NSFileManager defaultManager] attributesOfItemAtPath:filestring error:nil];
NSLog(#"Modified Day : %#", [filePathsArray1 objectForKey:NSFileModificationDate]);
}
NSFileManager* filemngr = [NSFileManager defaultManager];
NSDictionary* attributes = [filemngr attributesOfItemAtPath:path error:nil];
if (attributes != nil) {
NSDate *date = (NSDate*)[attributes objectForKey:NSFileModificationDate];
} else {
NSLog(#"File Not found !!!");
}
You can get your answer Here.
But only change you going to do is, you need to change NSFileCreationDate to NSFileModificationDate
NSDate *date = (NSDate*)[attrs objectForKey: NSFileModificationDate];

How to get data from property list into an NSArray programmatically?

I have generated a property list which save some hospital names. Now I want to get the names into an array from that plist. please help me. Thanx in advance.
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"plist"];
contentArray = [NSArray arrayWithContentsOfFile:plistPath];
try this
Try this
NSMutableDictionary* dictionary = [[[NSMutableDictionary alloc] init] autorelease];
NSError *error;
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* metadataPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"Metadata.plist"]];
[metadataPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:metadataPlistPath] ) {
NSString *pathToSettingsInBundle = [[NSBundle mainBundle]
pathForResource:#"Metadata" ofType:#"plist"];
[fileManger copyItemAtPath:pathToSettingsInBundle toPath:metadataPlistPath error:&error];
}
//Now read the plist file from Documents
NSString* myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"Metadata.plist"] ];
dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:myPlistPath];
return dictionary;
}
//fetch the data based on key
- (NSMutableArray*) fetchMetadataArrayForKey:(NSString*)aKey {
NSMutableArray* arrCategories = [[[NSMutableArray alloc] init] autorelease];
NSMutableDictionary* dictionary = [self fetchMetadata];
arrCategories = [dictionary valueForKey:aKey];
return arrCategories;
}

EXC_BAD_ACCESS - iPhone

My iPhone app is crashing and getting EXC_BAD_ACCESS error when using this code:
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"stats.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"stats" ofType:#"plist"]; //5
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
[bundle release];
}
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//load from savedStock example int value
score.highScore = [[savedStock objectForKey:#"score"] intValue];
score.deaths = [[savedStock objectForKey:#"deaths"] intValue];
score.iFallPoints = [[savedStock objectForKey:#"iFallPoints"] intValue];
score.difficulty = [[savedStock objectForKey:#"difficulty"] intValue];
[savedStock release];
score is the singleton I am accessing.
You didn't alloc or retain bundle; don't release it.
See the memory management programming guide if you need help understanding it.
Also, the static analyzer can be helpful for pointing some out memory bugs.