Overwriting a file programmatically in Cocoa - cocoa

This code copies the referenced file and places it in the Docs Directory. I'm trying to build a simple backup solution. The problem is this operation does not overwrite the existing file if the operation is repeated.
Two questions:
What's the best way to overwrite in code?
How difficult would it be to append the current date to each copied file? In this case there would be no overwrite operation. This would be much more useful for keeping incremental backups. If I decide to do it this way I understand I would need to create a new path in order to keep things organized.
Thanks.
Paul
NSString * name = #"testFile";
NSArray * files = [NSArray arrayWithObject: name];
NSWorkspace * ws = [NSWorkspace sharedWorkspace];
[ws performFileOperation: NSWorkspaceCopyOperation
source: #"~/Library/Application Support/testApp"
destination: #"~/Documents/"
files: files
tag: 0];

You could try using NSFileManager, example below (untested):
// Better way to get the Application Support Directory, similar method for Documents Directory
- (NSString *)applicationSupportDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
return [basePath stringByAppendingPathComponent:#"testApp"];
}
- (void) removeFile {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *applicationSupportDirectory = [self applicationSupportDirectory];
NSError *error = nil;
NSString* filePath = [applicationSupportDirectory stringByAppendingPathComponent: #"testFile"];
if ([fileManager fileExistsAtPath:filePath isDirectory:NULL]) {
[fileManager removeItemAtPath:filePath error:&error];
}
}
Edit:
Take a look at the NSFileManager Class Reference for other functions that might be useful (for your second question).

Related

Reading files from Documents directory using xcode

with reference to my own question,
UITable is not getting populated with NSMutableArray here i got all the file names into a table. And these files where stored in 'Resources' folder. Now i need to fill the same table from the files stored in a subfolder say 'sample' which is in documents folder of ios simulator.
Earlier i did this with the following code
files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:
[[NSBundle mainBundle] bundlePath] error:nil];
search_results_array = [files filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:#"self BEGINSWITH[cd] 'h'"]];
here both files and search_results_array are arrays. Now the reading is not from resources. How can i edity it? anybody please help.
Use the following:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //Library directory is not accessible via iTunes, Document directory is
NSString *docDirectory = [paths objectAtIndex:0]; //2
path = [docDirectory stringByAppendingPathComponent:yourString]; //3
files = [[NSDictionary alloc] initWithContentsOfFile: path];
Assuming files is an NSDictionary.

How to delete plist file

I know how to create plist file but I need to delete plist file.
But I don't know how to do this.
- (NSString *) save
{
NSArray *path =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[path objectAtIndex:0] stringByAppendingPathComponent:#"save.plist"];
}
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:myPath error:NULL];
you should use file io method and then delete the file! search file io in programming language your working

Problems adding data to a plist file

I've been trying to write data back to a pre-defined plist file (data.plist) in my bundle. Using the code below I call the routine 'dictionaryFromPlist' to open the file and then call 'writeDictionaryToPlist' to write to the plist file. However, no data gets added to the plist file.
NSDictionary *dict = [self dictionaryFromPlist];
NSString *key = #"Reports";
NSString *value = #"TestingTesting";
[dict setValue:value forKey:key];
[self writeDictionaryToPlist:dict];
- (NSMutableDictionary*)dictionaryFromPlist {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"plist"];
NSMutableDictionary* propertyListValues = [[NSMutableDictionary alloc]
initWithContentsOfFile:filePath];
return [propertyListValues autorelease];
}
- (BOOL)writeDictionaryToPlist:(NSDictionary*)plistDict{
NSString *filePath = #"data.plist";
BOOL result = [plistDict writeToFile:filePath atomically:YES];
return result;
}
The code runs through successfully and no error is thrown but no data is added to my plist file.
You can not write to your bundle, it is read only. If your case though, you are writing to a relative path, not to the bundle.
I'm not sure what the default working directory is for iOS apps. It is best to use absolute paths. You should be writing to the documents/cache directory. Something like this will get the path for you:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
Then just grab the lastObject and prepend that to your file name.
As mentioned by #logancautrell you can not write in mainbundle, you can save your plist in the app documents folder, you could do so:
NSString *path = #"example.plist";
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count]> 0)? [paths objectAtIndex: 0]: nil;
NSString *documentPath = [basePath stringByAppendingPathComponent:path] // Documents
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL checkfile = [fileManager fileExistsAtPath: documentPath];
NSLog(#"%#", (checkFile ? #"Exist": #"Not exist"));//check if exist
if(!checkfile) {//if not exist
BOOL copyFileToDoc = [yourDictionary writeToFile:documentPath atomically: YES];
NSLog(#"%#",(copyFileToDoc ? #"Copied": #"Not copied"));
}

Cocoa: Getting image file metadata

I am building an app that allows users to select a file and/or folder either locally or across the network and list the contents of that selection in a NSTableView after some filtering (no hidden files, only accepting .tif, .eps). The user can then select a file name from the list and then have the files metadata shown to them. At least that is what I want to happen. Right now I am getting null returned for the metadata. Here's my code:
- (void)tableViewSelectionDidChange:(NSNotification *)notif {
NSDictionary* metadata = [[NSDictionary alloc] init];
//get selected item
NSString* rowData = [fileList objectAtIndex:[tblFileList selectedRow]];
//set path to file selected
NSString* filePath = [NSString stringWithFormat:#"%#/%#", objPath, rowData];
//declare a file manager
NSFileManager* fileManager = [[NSFileManager alloc] init];
//check to see if the file exists
if ([fileManager fileExistsAtPath:filePath] == YES) {
//escape all the garbage in the string
NSString *percentEscapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)filePath, NULL, NULL, kCFStringEncodingUTF8);
//convert path to NSURL
NSURL* filePathURL = [[NSURL alloc] initFileURLWithPath:percentEscapedString];
NSError* error;
NSLog(#"%#", [filePathURL checkResourceIsReachableAndReturnError:error]);
//declare a cg source reference
CGImageSourceRef sourceRef;
//set the cg source references to the image by passign its url path
sourceRef = CGImageSourceCreateWithURL((CFURLRef)filePathURL, NULL);
//set a dictionary with the image metadata from the source reference
metadata = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(sourceRef,0,NULL);
NSLog(#"%#", metadata);
[filePathURL release];
} else {
[self showAlert:#"I cannot find this file."];
}
[fileManager release];
}
I'm guessing the problem here is the CFURLREF in CGImageSourceCreateWithURL. Instead of NSURL should I be using something else?
Thanks
Here's the path I am passing (logged from filePathURL): file://localhost/Volumes/STORAGE%20SVR/Illustration-Wofford/Illustration%20Pickup/Archive/AL013111_IL_Communication.eps
I can't tell where the "localhost" part in your file URL comes from, but I think that's the culprit. A file url doesn't usually contain a "localhost" part. In your example, it should look like this:
file:///Volumes/STORAGE%20SVR/Illustration-Wofford/Illustration%20Pickup/Archive/AL013111_IL_Communication.eps
But I'm pretty sure you've figured this out by now :)
Update: I stand corrected by Mike's comment: file://localhost/... is the same thing as file:///...!

Copy contents of Directories but excluding subdirectories in Cocoa

In Cocoa, is there any way to copy all the files in a directory without copying the directory's subdirectories along with them?
One way would be to copy items in the directory conditionally based on the results of NSFileManagers -fileExistsAtPath:isDirectory::
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *files = [manager contentsOfDirectoryAtPath:pathFrom error:nil];
for (NSString *file in files) {
NSString *fileFrom = [pathFrom stringByAppendingPathComponent:file];
BOOL isDir;
if (![manager fileExistsAtPath:fileFrom isDirectory:&isDir] || isDir) {
continue;
}
NSString *fileTo = [pathTo stringByAppendingPathComponent:file];
NSError *error = nil;
[manager copyItemAtPath:fileFrom toPath:fileTo error:&error];
if (error) // ...
}

Resources