loading data from plist to another class - iphone

In my app, plist files are being saved to the documents directory, each file name is the current date+time.
I'm loading the list of files from the documents directory to a table: filesTableVC.m.
Each time I want to load the chosen file to a new class: oldFormVC.m
but this class is opened empty.
I'm not sure where the problem is.
filesTableVC.m:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
oldFormVC *oldForm = [[oldFormVC alloc] initWithNibName:nil bundle:nil];
//load previous data:
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:[fileList objectAtIndex:indexPath.row]];
// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
// if not in documents, get property list from main bundle
plistPath = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
}
// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property liost into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
// assign values
self.theDate = [temp objectForKey:#"theDate"];
self.theTime = [temp objectForKey:#"theTime"];
self.carNumber = [temp objectForKey:#"carNumber"];
self.driverName = [temp objectForKey:#"driverName"];
[self presentViewController:oldForm animated:YES completion:nil];
}
oldFormVC.m:
- (void)viewDidLoad
{
[super viewDidLoad];
dateField.text = theDate;
timeField.text = theTime;
carNumberField.text = carNumber;
driverNameField.text = driverName;
}

Write your code in viewDidAppear
- (void)viewDidAppear:(BOOL)animated
{
dateField.text = theDate;
timeField.text = theTime;
carNumberField.text = carNumber;
driverNameField.text = driverName;
}
Also, change this code in filesTableVC.m:
oldForm.dateField = [temp objectForKey:#"theDate"];
oldForm.theTime = [temp objectForKey:#"theTime"];
oldForm.carNumber = [temp objectForKey:#"carNumber"];
oldForm.driverName = [temp objectForKey:#"driverName"];
Hope it helps you

Related

File search with specific Extension Objective c

I am working on some file manipulation in iPhone project. Where i need to search files of specific extension. One option is to manually process each file & directory to find.
My Question is, Is there any simple way to do that ?
Thanks
see using NSFileManager you can get the files and bellow the condition with you can get file with particular extension, Its work in Document Directory ..
-(NSArray *)findFiles:(NSString *)extension
{
NSMutableArray *matches = [[NSMutableArray alloc]init];
NSFileManager *manager = [NSFileManager defaultManager];
NSString *item;
NSArray *contents = [manager contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] error:nil];
for (item in contents)
{
if ([[item pathExtension]isEqualToString:extension])
{
[matches addObject:item];
}
}
return matches;
}
use this array with your searched files.. get the return in NSArray type so use NSArray object to store this data...
i hope this helpful to you...
I have not found any thing which i could say is simple to do that & and finally i have to write my own code to do this. I am posting this here because maybe someone find this help full.
-(void)search{
#autoreleasepool {
NSString *baseDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSFileManager *defFM = [NSFileManager defaultManager];
BOOL isDir = YES;
NSArray *fileTypes = [[NSArray alloc] initWithObjects:#"mp3",#"mp4",#"avi",nil];
NSMutableArray *mediaFiles = [self searchfiles:baseDir ofTypes:fileTypes];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:#"playlist.plist"];
if(![defFM fileExistsAtPath:filePath isDirectory:&isDir]){
[defFM createFileAtPath:filePath contents:nil attributes:nil];
}
NSMutableDictionary *playlistDict = [[NSMutableDictionary alloc]init];
for(NSString *path in mediaFiles){
NSLog(#"%#",path);
[playlistDict setValue:[NSNumber numberWithBool:YES] forKey:path];
}
[playlistDict writeToFile:filePath atomically:YES];
[[NSNotificationCenter defaultCenter] postNotificationName:#"refreshplaylist" object:nil];
}
}
Now the recursive Method
-(NSMutableArray*)searchfiles:(NSString*)basePath ofTypes:(NSArray*)fileTypes{
NSMutableArray *files = [[[NSMutableArray alloc]init] autorelease];
NSFileManager *defFM = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *dirPath = [defFM contentsOfDirectoryAtPath:basePath error:&error];
for(NSString *path in dirPath){
BOOL isDir;
path = [basePath stringByAppendingPathComponent:path];
if([defFM fileExistsAtPath:path isDirectory:&isDir] && isDir){
[files addObjectsFromArray:[self searchfiles:path ofType:fileTypes]];
}
}
NSArray *mediaFiles = [dirPath pathsMatchingExtensions:fileTypes];
for(NSString *fileName in mediaFiles){
fileName = [basePath stringByAppendingPathComponent:fileName];
[files addObject:fileName];
}
return files;
}
What you need is a recursive method so that you can process sub-directories. The first of the following methods is public; the other private. Imagine they are implemented as static methods of a class called CocoaUtil:
CocoaUtil.h:
#interface CocoaUtil : NSObject
+ (NSArray *)findFilesWithExtension:(NSString *)extension
inFolder:(NSString *)folder;
#end
CocoaUtil.m:
// Private Methods
#interface CocoaUtil ()
+ (NSArray *)_findFilesWithExtension:(NSString *)extension
inFolder:(NSString *)folder
andSubFolder:(NSString *)subFolder;
#end
#implementation CocoaUtil
+ (NSArray *)findFilesWithExtension:(NSString *)extension
inFolder:(NSString *)folder
{
return [CocoaUtil _findFilesWithExtension:extension
inFolder:folder
andSubFolder:nil];
}
+ (NSArray *)_findFilesWithExtension:(NSString *)extension
inFolder:(NSString *)folder
andSubFolder:(NSString *)subFolder
{
NSMutableArray *found = [NSMutableArray array];
NSString *fullPath = (subFolder != nil) ? [folder stringByAppendingPathComponent:subFolder] : folder;
NSFileManager *fileman = [NSFileManager defaultManager];
NSError *error;
NSArray *contents = [fileman contentsOfDirectoryAtPath:fullPath error:&error];
if (contents == nil)
{
NSLog(#"Failed to find files in folder '%#': %#", fullPath, [error localizedDescription]);
return nil;
}
for (NSString *file in contents)
{
NSString *subSubFolder = subFolder != nil ? [subFolder stringByAppendingPathComponent:file] : file;
fullPath = [folder stringByAppendingPathComponent:subSubFolder];
NSError *error = nil;
NSDictionary *attributes = [fileman attributesOfItemAtPath:fullPath error:&error];
if (attributes == nil)
{
NSLog(#"Failed to get attributes of file '%#': %#", fullPath, [error localizedDescription]);
continue;
}
NSString *type = [attributes objectForKey:NSFileType];
if (type == NSFileTypeDirectory)
{
NSArray *subContents = [CocoaUtil _findFilesWithExtension:extension inFolder:folder andSubFolder:subSubFolder];
if (subContents == nil)
return nil;
[found addObjectsFromArray:subContents];
}
else if (type == NSFileTypeRegular)
{
// Note: case sensitive comparison!
if ([[fullPath pathExtension] isEqualToString:extension])
{
[found addObject:fullPath];
}
}
}
return found;
}
#end
This will return an array containing the full path to every file with the specified file extension. Note that [NSString pathExtension] does not return the . of the file extension so be sure not to pass that in the extension parameter.
Yes we have direct method for NSArray below helps you
NSMutableArray *arrayFiles = [[NSMutableArray alloc] initWithObjects:#"a.png", #"a.jpg", #"a.pdf", #"h.png", #"f.png", nil];
NSLog(#"pathsMatchingExtensions----%#",[arrayFiles pathsMatchingExtensions:[NSArray arrayWithObjects:#"png", nil]]);
//my output is
"a.png",
"h.png",
"f.png"
Like this way you can find your specific file extension
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
NSString *filename;
while ((filename = [direnum nextObject] )) {
if ([filename hasSuffix:#".doc"]) { //change the suffix to what you are looking for
[arrayListofFileName addObject:[filename stringByDeletingPathExtension]];
}
}
Use below code
NSArray *myFiles = [myBundle pathsForResourcesOfType:#"Your File extension"
inDirectory:nil];

Save text in plist file with specific date

I am trying to store some stings into a plist file, the saving process works fine, but these notes should be saved based on a specific date, for example I enter a note on 2 Feb then I need enter another note on 5 Feb, and when I move during these dates my notes should show on these dates. I would be grateful if you help me.
Here is my code:
//Save Setting ///////////////////
- (NSString *) saveFilePath
{
NSArray *pathArray =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSDate *date = [NSDate date];
return [[pathArray objectAtIndex:0] stringByAppendingPathComponent:#"note.plist"];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
NSArray *values = [[NSArray alloc] initWithObjects:saveTextToday.text ,nil];
[values writeToFile:[self saveFilePath] atomically:YES];
[values release];
}
- (void)viewDidLoad
{
////Save Setting /////////////////////////////////////////////////
NSString *myPath = [self saveFilePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
if (fileExists)
{
NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];
saveTextToday.text = [values objectAtIndex:0];
[values release];
}
// notification
UIApplication *myApp = [UIApplication sharedApplication];
// add yourself to the dispatch table
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationWillTerminate:)
name:UIApplicationWillTerminateNotification
object:myApp];
}
It appears you're saving an array to a file, but using a ".plist" file extension. While the file created will be a plist file, there is no date information in the content.
Instead of an array, you could use an NSDictionary. Use the current date as the key, and the array you're using now as the object. Like this:
NSMutableDictionary *myDictionary = [NSMutableDictionary alloc] initWithContentsOfFile:myPath];
NSString *todayKey = [self showPersianFullDate]; // or [self showPersianFullDate:[NSDate date]]
[myDictionary setObject:saveTextToday.text forKey:todayKey];
[myDictionary writeToFile:[self saveFilePath] atomically:YES];
I think what you want to do is use the NSFileManager to find out when the file was saved, like this:
NSString *path = #"the path you've saved you plist to";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDate *creationDate = nil;
if ([fileManager fileExistsAtPath:path])
{
NSError *error = nil;
NSDictionary *attributes = [fileManager attributesOfItemAtPath:path error:&error];
creationDate = [attributes objectForKey:NSFileCreationDate];
}
creationDate now contains the date when the file was first saved. To get the date when it was last saved, use NSFileModificationDate instead.

How to sort files by modified date in iOS

I used NSFileManager to retrieve the files in a folder, and I want to sort them by modified date. How to do that ?
Thanks.
What have you tried so far?
I haven't done this, but a quick look at the docs makes me think that you should try the following:
Call -contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: and specify NSURLContentModificationDateKey as one of the keys.
You'll get back an array of NSURL objects which you can then sort using an NSArray method like -sortedArrayUsingComparator:.
Pass in a comparator block that looks up the modification date for each NSURL using -getResourceValue:forKey:error:.
Update: When I wrote the answer above, -getResourceValue:forKey:error: existed in iOS but didn't do anything. That method is now functional as of iOS 5. The following code will log an app's resource files followed by a list of corresponding modification dates:
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *files = [manager contentsOfDirectoryAtURL:[[NSBundle mainBundle] resourceURL]
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLContentModificationDateKey]
options:nil
error:nil];
NSMutableArray *dates = [NSMutableArray array];
for (NSURL *f in files) {
NSDate *d = nil;
if ([f getResourceValue:&d forKey:NSURLContentModificationDateKey error:nil]) {
[dates addObject:d];
}
}
NSLog(#"Files: %#", files);
NSLog(#"Dates: %#", dates);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *imageFilenames = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSMutableArray *originalImage = [[NSMutableArray alloc]init];
for (int i = 1; i < [imageFilenames count]; i++)
{
NSString *imageName = [NSString stringWithFormat:#"%#/%#",documentsDirectory,[imageFilenames objectAtIndex:i] ];
}
//---------sorting image by date modified
NSArray* filelist_date_sorted;
filelist_date_sorted = [imageFilenames sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
NSDictionary* first_properties = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:#"%#/%#", documentsDirectory, obj1] error:nil];
NSDate *first = [first_properties objectForKey:NSFileCreationDate];
NSDictionary *second_properties = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:#"%#/%#", documentsDirectory, obj2] error:nil];
NSDate *second = [second_properties objectForKey:NSFileCreationDate];
return [second compare:first];
}];
NSLog(#" Date sorted result is %#",filelist_date_sorted);
static static NSInteger contentsOfDirSort(NSString *left, NSString *right, void *ptr) {
(void)ptr;
struct stat finfo_l, r_finfo_r;
if(-1 == stat([left UTF8String], &finfo_l))
return NSOrderedSame;
if(-1 == stat([right UTF8String], &finfo_r))
return NSOrderedSame;
if(finfo_l.st_mtime < finfo_r.st_mtime)
return NSOrderedAscending;
if(finfo_l.st_mtime > finfo_r.st_mtime)
return NSOrderedDescending;
return NSOrderedSame;
}
Now, later on in your code.
NSMutableArray *mary = [NSMutableArray arrayWithArray:filePathsArray];
[mary sortUsingFunction:contentsOfDirSort context:nil];
// Use mary...
Quick Method:
-(void)dateModified
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
//--- Listing file by name sort
NSLog(#"\n File list %#",fileList);
int num;
//-- Listing file name with modified dated
for (NSString *s in fileList)
{
NSString *filestring = [documentsDirectory stringByAppendingFormat:#"/%#",s];
NSDictionary *filePathsArray1 = [[NSFileManager defaultManager] attributesOfItemAtPath:filestring error:nil];
NSString *modifiedDate = [filePathsArray1 objectForKey:NSFileModificationDate];
NSLog(#"\n Modified Day : %#", modifiedDate);
num=num+1;
}
}
In a category over NSFileManager:
static NSInteger contentsOfDirSort(NSURL *leftURL, NSURL *rightURL, void *ptr)
{
(void)ptr;
NSDate * dateLeft ;
[leftURL getResourceValue:&dateLeft
forKey:NSURLContentModificationDateKey
error:nil] ;
NSDate * dateRight ;
[rightURL getResourceValue:&dateRight
forKey:NSURLContentModificationDateKey
error:nil] ;
return [dateLeft compare:dateRight];
}
- (NSArray *)contentsOrderedByDateOfDirectoryAtPath:(NSURL *)URLOfFolder ;
{
NSArray *files = [self contentsOfDirectoryAtURL:URLOfFolder
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLContentModificationDateKey]
options:0
error:nil];
return [files sortedArrayUsingFunction:contentsOfDirSort
context:nil] ;
}

Objective-c: How to handle errors when loading a simple txt file

I'm trying to load a simply TXT file into a NSMutableArray. My file is called NoteBook.txt. For the following purposes (handling errors), I deleted NoteBook.txt so that the App could actually NOT load it.
In the following code, I try to find out if the file exist in my Docs Folder which I'd like to load. The following code should actually NOT attempt to load the file as there isn't one. However, it does so nonetheless and I am wondering what I am doing wrong?
Imagine that the string #"NoteBook.txt" is passed to the following method and that there is no such file in the Docs Folder of the App:
-(void) loadNoteBook:(NSString *)nameOfNoteBook
{
NSLog(#"Starting method 'LoadNoteBook...'");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
//NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"NoteBook.txt"];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:nameOfNoteBook];
NSError *error;
if (filePath) { // check if file exists - if so load it:
NSLog(#"Loading notebook: %#", nameOfNoteBook);
NSString *tempTextOut = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&error];
self.NoteBook = [[[tempTextOut componentsSeparatedByString: #"\n*----------*\n"] mutableCopy] autorelease];
}
else
{
// GENERATE mutable ARRAY
NSLog(#"Loading notebook failed, creating empty one...");
NoteBook = [[NSMutableArray alloc] init];
for (int temp = 0; temp < 6; temp++) {
[NoteBook insertObject:#"Empty" atIndex:temp];
}
}
}
Thanks for any suggestions, I'd really appreciate your help.
The problem is that you're checking if the NSString is set, not the path itself.
What you should probably do is check the path with NSFileManager fileExistsAtPath:isDirectory:
BOOL isDir;
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
if ([fileManager fileExistsAtPath:filePath isDirectory:&isDir] && !isDir) {
//file exists and is not a directory
}
You've got it already in your code:
NSString *tempTextOut = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&error];
if(!tempTextOut) {
if(error) {
// error specific code to execute
NSLog(#"error loading file %#: %#", filePath, error);
}
// GENERATE mutable ARRAY
NSLog(#"Loading notebook failed, creating empty one...");
NoteBook = [[NSMutableArray alloc] init];
for (int temp = 0; temp < 6; temp++) {
[NoteBook insertObject:#"Empty" atIndex:temp];
}
} else {
self.NoteBook = [[[tempTextOut componentsSeparatedByString: #"\n*----------*\n"] mutableCopy] autorelease];
}
You test on filePath, which is actually just a string you've created. You don't test if there is a file behind it. Even if
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
does return an empty string you still append nameOfNoteBook to it and will if put in an if statement, testing against a non empty string will evaluate to true.

Plist file path error?

I am trying to save an NSMutableArray containing text to a plist file using this code:
- (IBAction)saveDoc:(id)sender
{
NSString *typedText = typingArea.text;
NSMutableArray *totalFiles = [[NSMutableArray alloc] initWithObjects:typedText, nil];
NSLog(#"Created: %#", totalFiles);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"savedFiles.plist"];
NSLog(#"Found Path: %#", path);
//[totalFiles addObject:typedText];
[totalFiles writeToFile:path atomically:YES];
NSLog(#"File Written: %# to: %#", totalFiles, path);
[totalFiles release];
NSLog(#"Released: %#", totalFiles);
}
All of the NSLogs return appropriate values as expected. I use this code to crate a new NSMutableArray with the contents of the plist:
- (void)viewDidLoad {
file = [[NSBundle mainBundle] pathForResource:#"savedFiles" ofType:#"plist"];
NSLog(#"Got Path: %#", file);
array = [NSMutableArray arrayWithContentsOfFile:file];
NSLog(#"Loaded Array into new array: %#", array);
//UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"fdsfasdf" message:[dic objectForKey:#"item1"] delegate:self cancelButtonTitle:#"ldfghjfd" otherButtonTitles:nil] autorelease];
//[alert show];
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
The NSLogs in this code come back with a slightly different path than the first one returned with. It also said the array is (null)
How should I load the contents from a plist file?
Thanks in advance,
Tate
Try initialising your array first:
array = [[NSMutableArray alloc] initWithContentsOfFile:file];