My NSArray is:
self.files = [bundle pathsForResourcesOfType:#"ppt" inDirectory:#"thepowerpoints"];
This returns the full path of
/User/Name/.../filename.ppt
I can use a NSString to get only the filename using:
NSString *documentsDirectoryPath = [self.files objectAtIndex:thepath.row];
self.filenames = [[documentsDirectoryPath lastPathComponent] stringByDeletingPathExtension];
Is there a way that I can cleanup the original NSArray to only return the lastPathComponent without the extension?
Am needing to do this to search within the tableview array. Currently, if a file is named "Test.ppt" the search bar will show it if I type in "/User/Name", because the Array it is searching includes the entire path.
I would prefer for it to only search the filename.
NSMutableArray *names = [NSMutableArray arrayWithCapacity:[self.files count]];
for (NSString *path in self.files) {
[names addObject:[[path lastPathComponent] stringByDeletingPathExtension]];
}
self.files = names;
Related
I've been trying to save to a property list file, however it's not working as its only saving the object to the array not the actual file itself, meaning that what it saves isn't obviously persisting.
[[category objectAtIndex:questionCounter] replaceObjectAtIndex:5 withObject:myString];
[category writeToFile:filePath atomically:YES];
I'm using this earlier on to save the property list files to the document directory so that I can edit and save to them:
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistFilePath = [documentsDirectory stringByAppendingPathComponent:fileNameFull];
if([[NSFileManager defaultManager] fileExistsAtPath:plistFilePath]) {
category = [NSMutableArray arrayWithContentsOfFile:plistFilePath];
NSLog(#"Files exist.");
}
else {
filePath = [[NSBundle mainBundle] pathForResource:fileNamer ofType:#"plist"];
category = [NSMutableArray arrayWithContentsOfFile:filePath];
NSLog(#"Files have been created.");
}
My property list is made up of arrays, within those arrays I'm trying to save my object (the string). I have a feeling it's something trivial but I can't spot it.
When you are trying to save your array, you are passing in filePath which points to the main bundle directory, which you can't write to. You want to use plistFilePath instead, like so:
[category writeToFile:plistFilePath atomically:YES];
I am developing an application where i am creating some random .txt file which ultimately stored as a txt file format.
Now for reading these file i am using this code
NSString* documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError* error = nil;
myArray = [[[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirectory error:&error]retain];
Now i am displaying the file name in a table view using
cell.textLabel.text = [myArray objectAtIndex:row];
So it curretly displaying like file1.txt,file2.txt etc.
But i donot want the file extension while displaying in the table list.
How can i do that?
cell.textLabel.text = [[myArray objectAtIndex:row] stringByDeletingPathExtension];
Use [yourString stringByDeletingPathExtension] method to remove the extensions from your string. Refer NSString class.
How to read the Contents of the CSV file to an array in the objective c..
I Have a CSV file where i need to read the contents of it in a array.
Try this - Here, I expect a file array.out in documents directory. This file I read it into an NSArray and iterate through it...
// Get path to documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
if([paths count] > 0)
{
// Path to save array data
NSString *arrayPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"array.out"];
// Read both back in new collections
NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:arrayPath];
for (NSString *element in arrayFromFile)
NSLog(#"Beer: %#", element);
}
NSString provides some high level support for this.
to read the file, use something like this:
NSString * file = [[NSString alloc] initWithContentsOfFile:path
encoding:encoding error:&error];
then to divide the string, use something like:
NSArray * values = [file componentsSeparatedByString:separator];
or
NSArray * values = [file componentsSeparatedByCharactersInSet:separatorSet];
I had a look around, trying to find a straightforward method for first saving a MutableArray (which will contain different text arrays from UITextViews with returns etc.) into a txt-file and then loading the txt-file back into my MutableArray.
I didn't manage to come up with the reverse method (loading the text-file) and was wondering how I should go about this. I'm sure txt files and mutable arrays are not really compatible, especially if I want the MutableArray to hold various text strings from UITextViews.
Is there a way to mark the beginning of one section in a mutable array and the beginning of the next in a txt file? The aim would be to be able to edit the txt file both in the program and in a simple text editor without messing up the structure of the mutable array.
Can I use a certain special character (not \n obviously) in my text file so as to separate different objects?
Here is what I've come up with so far. Sorry, I'm a beginner and it's very basic. The first problem is that I get the error message 'NSMutableArray' may not respond to '-writeToFile:atomically:encoding:error:'. Next, I have no idea how to load the txt back into my Array. Finally, I'd like to come up with a way to separate the arrays in the txt so that it remains editable, but that would be the absolute icing. Perhaps a solution would be to save each Object in an Array in a separate txt file and then load each txt into the array?
// GENERATE ARRAY
NoteBook = [[NSMutableArray alloc] init];
for (int temp = 0; temp < 3; temp++) {
[NoteBook insertObject:#"Title\n\n Line1\nLine2..." atIndex:temp];
}
// SAVING MY MUTABLE ARRAY
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error;
BOOL succeed = [NoteBook writeToFile:[documentsDirectory stringByAppendingPathComponent:#"myfile.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
// Handle error here
}
// LOADING TEXTFILE AND PUT IT INTO A MUTABLE ARRAY
// NO IDEA... how to do this
Convert your arrays into strings, and vice versa, using, e.g.,
NSString* arrayText = [NoteBook componentsJoinedByString: #"<your-favourite-separator-string>"];
the write to file using [arrayText writeToFile...]
After reading a string back from a file, use
Notebook = [arrayText componentsSeparatedByString: #"<your-favourite-separator-string>"];
Lastly, don't do this. Save your array directly to a property list (read up on those) or JSON or some other structured data format.
Why not just turn the mutable array into JSON and write that string to a file? The inverse is to read the string from file and turn back into an array using the JSON parser. json-framework is very easy to use.
A benefit would be that you could create or modify your array by editing text files as long as you write valid JSON.
make NSMutableArray to NSArray .because NSMutableArray does not have writeToFile .
retriev array from file
NSArray *theCatalogInfo=nil;
NSString *theCatalogFilePath = [NSString stringWithFormat:#"%#/Documents/",NSHomeDirectory()];
theCatalogFilePath = [theCatalogFilePath stringByAppendingString:kCatalogCachePath];
if(nil!=theCatalogFilePath)
{
theCatalogInfo=[[NSArray alloc]initWithContentsOfFile:theCatalogFilePath];
}
Save array To file
NSString *theCatalogFilePath = [NSString stringWithFormat:#"%#/Documents/",NSHomeDirectory()];
theCatalogFilePath = [theCatalogFilePath stringByAppendingString:kCatalogCachePath];
[**YourArray** writeToFile:theCatalogFilePath atomically:YES];
Have a look at following three methods to create a text file, write to it and read the data from it.
The key is to store the different objects separated by space. And you should get it very simple.
-(void)createFile
{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Sample.txt"];
NSFileManager * file_manager = [NSFileManager defaultManager];
if(![file_manager fileExistsAtPath:filePath])
{
[file_manager createFileAtPath:filePath contents:nil attributes:nil];
NSString *content = #"NULL NULL NULL";
[content writeToFile:filePath
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
}
-(void)writeToFile
{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Sample.txt"];
NSString *content = [NSString stringWithFormat:#"%# %# %#", obj1, obj2, obj3];
[content writeToFile:filePath
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
-(void)readFromFile
{
objects = [[NSArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Sample.txt"];
if (filePath) {
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSASCIIStringEncoding error:nil];
if (myText) {
objects = [myText componentsSeparatedByString:#" "];
}
}
}
if your nsarray contains nsdictionary, nsarray, nsstring, nsnumber, nsdata or nsdate objects (no custom objects, int's, etc) you can simply write the contents of your mutable array to a plist file.
this will maintain the data structure you have and you can simply read that data right into an array. How I do it in a couple of my data classes is
NSArray *tempArray = [NSArray arrayWithContentsOfFile:[Utils getFileLocation]];
if (tempArray == nil) {
yourArray = [[NSMutableArray alloc] init];
} else {
yourArray = [[NSArray deepMutableCopy:tempArray] retain];
}
I have some string that have a type like this
NSString *string1 = #"/Users/mine/Library/Application Support/iPhone Simulator/3.2/Applications/02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php";
if i just want to get the "02221798-1B7A-46B4-928F-F5BE37E177B5"
i have implement a code like this :
NSString *subString1;
int count = [string1 length];
NSLog(#"count : %d", count);
subString1 = [string1 substringFromIndex:121];
but it left "02221798-1B7A-46B4-928F-F5BE37E177B5/Documents/Project/Project 1/Folder 1/2.php"
how can i do to fix it??
To get the name of your app's parent directory you should try this instead:
NSString *appUUID = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] lastPathComponent];
This will work both on a device and Simulator.
If you need to get the full path to the Documents folder inside your app sandbox:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
If you need to append a path component to a path string:
NSString *projectPath = [documentsPath stringByAppendingPathComponent: #"Project"];
Please, take a look at NSString documentation, section "Tasks", "Working with Paths". It is a must-read.
you can use stringWithRange method of NSString.
subString1 = [string1 stringWithRange:NSMakeRange(startPos,yourLengthToSelect)];
or you can use componentSeparetedByString and break string using #"/". it will return array of string. get your desired string using array index.