Delete a line of text in txt file iOS - iphone

Is it possible to delete a line of text that store in .txt file. I am currently successful to extract each line inside txt file and add into array then display each line in TableView. Now I if I want to delete particular line How do I do it?

Put the strings from your NSArray into a NSMutableArray, delete the line that you want deleted, convert to a single NSString by joining elements with #"\n" string, and then write the string to file, like this:
NSMutableArray *tmp = [myArray mutableCopy];
[tmp removeObjectAtIndex:indexToRemove];
NSString *tmpStr = [NSString componentsJoinedByString:#"\n"];
NSError *err = nil;
[tmpStr writeToFile:myFile
atomically:NO
encoding:NSUTF8StringEncoding // <== use an encoding that you need
error:&err];

Related

Json Values on Screen Objective c

NSDictionary *allDatDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *responseData = [allDatDictionary objectForKey:#"responseData"];
NSDictionary *arrayOfResult = [responseData objectForKey:#"results"];
for (NSDictionary *diction in arrayOfResult) {
NSString *title = [diction objectForKey:#"title"];
NSString *content = [diction objectForKey:#"content"];
NSString *url = [diction objectForKey:#"url"];
[array addObject:title];
[content1 addObject:content];
[url1 addObject:url];
NSLog(#"title: %#, \n Content: %# \n, Url: %# \n", [diction objectForKey:#"title"], [diction objectForKey:#"content"],[diction objectForKey:#"url"]);
NSString *text = #"";
text = [NSString stringWithFormat:#"Title: %#%#\nURL: %#\nContent: %#\n\n", text, [diction objectForKey:#"title"],[diction objectForKey:#"url"],[diction objectForKey:#"content"]];
Hey guys, I got the json and I need to show title, content and url on screen. I don't need table ranting like this just show on screen. NSLog shows everything but when I try to write on a UILabel it just shows 1 result. Any tips how I can do that? thanks
You're setting labelTitle's text in a for loop, so you're only going to see the last result, because you keep changing it each time thru the loop. If you want to see all of the results, you'll have to build up a string that contains all of them and then set that as the text of the label.
At the top of the for loop, declare an NSString variable and set it to #"", like the following:
NSString *text = #"";
Then each time thru the loop, instead of setting the label text to your string, build up this string that you're saving at the top, like the following:
text = [NSString stringWithFormat:#"%#%#\n", text, [diction objectForKey:#"title"]];
You can see how I modified that format string. It takes the previous text you've saved, adds to it your new title, and then adds a carriage return.
As an alternative, you could have an NSMutableArray at the top, and add your strings to that array each time you go thru the for loop. Then at the end, you can use the NSArray method componentsJoinedByString:, using a carriage return as the separator, to get an NSString containing all of the individual strings that you added to the array.
After you have this one string, using either of these methods, you can set that as the text on the label.

Using writeToFile:atomically: consecutively doesn't work...why?

I'm trying to write a csv file. I have two arrays at hand - one with the titles (Name, Number etc), another with the actual values (Jon, 123 ...).
Now, after the following two operations:
[[titles componentsJoinedByString:#", "] writeToFile:file atomically:YES];
[[values componentsJoinedByString:#", "] writeToFile:file atomically:YES];
only the values array is written to the file. I realise that I may need to open the file again, but how do I do that after writing the first array? Or what is it exactly that I'm doing wrong if this is not the case?
Thanks!
The second line is in fact overwriting the file you wrote in the first line. One simple way to get around this problem would be to simply append the second string to the first (likely with an '\n' in between since you're making a csv file) and writing that string to your file:
NSString *str1 = [[titles componentsJoinedByString:#", "];
NSString *str2 = [[values componentsJoinedByString:#", "];
NSString *outputStr = [str1 stringByAppendingFormat:#"\n%#", str2];
[outputStr writeToFile:file atomically:YES];
Second time it replaces the old contents. So you could read the old content, append the old content with the new content and save on file.
Write first row
[[titles componentsJoinedByString:#", "] writeToFile:file atomically:YES];
Where you need to add another row every time
NSString *previousContent = [[NSString alloc] initWithContentsOfFile:file usedEncoding:nil error:nil];
NSString *str2 = [[values componentsJoinedByString:#", "];
NSString *outputStr = [previousContent stringByAppendingFormat:#"\n%#", str2];
[outputStr writeToFile:file atomically:YES];

How to not include file extension while reading from Document directory?

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.

reading arabic text from a txt file in iphone

I am working on app where I need to display arabic text from a text file. I am using following code:
NSString *fileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSArray *lines = [fileContents componentsSeparatedByString:#"\n"];
NSLog(#"%#",[lines objectAtIndex:0]);
I get about 60 records in this array lines. But when I try to print the data it does not print anything.
If the file starts with a newline, the first element in lines will be just an empty string. Try printing out the whole array instead, just to verify that your code is working as intended:
NSLog(#"%#", lines);

Convert Excel document (xls) to a plist

I have a pretty straightforward Excel spreadsheet, and I need to use the data in an iPhone app. The xls document has 6 columns, and > 200 rows.
I would like to create a plist from the xls document. How can I convert one to the other, programmatically?
I'm late to the party but I built a desktop utility that will convert CSV to a plist. You can download the binary or use this code, which requires cCSVParse. It uses whatever is in row 0 to create key names, then generates dictionaries for each successive row.
CSVParser *parser = [CSVParser new];
[parser openFileWithPath:pathAsString];
NSMutableArray *csvContent = [parser parseFile];
[parser closeFile];
if (pathAsString != nil)
{
NSArray *keyArray = [csvContent objectAtIndex:0];
NSMutableArray *plistOutputArray = [NSMutableArray array];
NSInteger i = 0;
for (NSArray *array in csvContent)
{
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSInteger keyNumber = 0;
for (NSString *string in array)
{
[dictionary setObject:string forKey:[keyArray objectAtIndex:keyNumber]];
keyNumber++;
}
if (i > 0)
{
[plistOutputArray addObject:dictionary];
}
i++;
}
NSMutableString *mutableString = [NSMutableString stringWithString:pathAsString];
[mutableString replaceOccurrencesOfString:#".csv" withString:#".plist" options:nil range:NSMakeRange([mutableString length]-4, 4)];
NSURL *url = [NSURL fileURLWithPath:mutableString];
[plistOutputArray writeToURL:url atomically:YES];
You could do this using a simple formula that you copy and pasted down a column beside each of your 200+ rows.
For example, assuming colum A contains a list of names, and column B contains a matching set of ages you could use a formula such as the following to end up with most of the XML for a plist based dictionary.
=CONCATENATE("<key>Name</key><string>", A1,"</string><key>Age</key><integer>",B1,"</integer>")
You then select all the cells within this new column you can copy and paste into notepad or another text editor to save it as a plist file (you may want to put some hardcoded text into a cell above and below your 200+ rows, in order to get the required tags etc as well...
Ladies and gentlemen,
I tried any other recommended solutions above but because of Unicode characters in my language (Turkish) none of them worked out for me... All unicode characters were all broken. Then I decided to make a tool for this.
I proudly present the simplest way to convert any XLS or XLSX or CVS file to a plist:
http://exceltoplist.herokuapp.com/
Just upload your XLS, XLSX or CSV and download your Apple Plist!
Enjoy!
Note: Because of Heroku's free dyno policy it might take a few moments to browse the page. Just keep waiting for 5-10 seconds to open page.
For OpenOffice, use this formula
=CONCATENATE("<key>number</key><integer>"; A2;"</integer><key>MyString</key><string>";B2;"</string>")
I found the CONCATENATE to work the best for this.
For my purpose I just need to convert CSV with two columns to plist file.
First column is keys and second are values. So, I slightly change Danilo Campos code as following:
CSVParser *parser = [CSVParser new];
[parser openFileWithPath:pathAsString];
NSMutableArray *csvContent = [parser parseFile];
[parser closeFile];
if (pathAsString != nil)
{
NSMutableDictionary *plistOutputArray = [NSMutableDictionary dictionary];
for (NSArray *array in csvContent)
{
NSString *key = (NSString *)([array objectAtIndex:0]);
NSString *value = (NSString *)([array objectAtIndex:1]);
[plistOutputArray setObject:value forKey:key];
}
NSMutableString *mutableString = [NSMutableString stringWithString:pathAsString];
[mutableString replaceOccurrencesOfString:#".csv" withString:#".plist" options:nil range:NSMakeRange([mutableString length]-4, 4)];
NSURL *url = [NSURL fileURLWithPath:mutableString];
[plistOutputArray writeToURL:url atomically:YES];
}
P.S. You can find his initial source code here - http://code.google.com/p/danilobits/source/checkout
Please note that to get his code work now you need to change "Base SDK" to "Latest OS X"
Use http://shancarter.github.io/mr-data-converter/ to convert xls to a Json(just copy & paste)(can re format it by remove white space in http://jsonviewer.stack.hu/). save json to text file named: in.json.
Use plutil command to format json to plist
plutil -convert xml1 in.json -o out.plist