Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append new line to string

Tags:

ios

nsstring

Hi I'm generating a string which consists of text entries from text fields.

NSString * lines = [NSString stringWithFormat:@"%@,%@,%@,%@,%@", [self.crabText text], [self.trawlText text], [self.trapText text], [self.vesselText text], [self.lengthText text]];

I generate the above string when the user selects a "Generate CSV" UIButton which follows by an IBAction. However, I then want to clear the text fields and append the new populated entries on top of the previous ones. However, only the current text field entries will be populated due to the function always creating a new instance of the "lines" string.

lines = [NSString stringWithFormat: @"%@\n", lines];

I have this working by putting all new strings into an array but was wondering if it were possible to just use the same string. An example would be "1,1,1,1,1" "new line" "2,2,2,2,2".

like image 207
user2402616 Avatar asked Jan 20 '26 00:01

user2402616


2 Answers

Don't do this:

NSString * lines = [NSString stringWithFormat:@"%@,%@,%@,%@,%@", [self.crabText text], [self.trawlText text], [self.trapText text], [self.vesselText text], [self.lengthText text]];

Do this:

NSArray *fields = @[[self.crabText text],
                   [self.trawlText text],
                   [self.trapText text],
                   [self.vesselText text],
                   [self.lengthText text]];
NSString *line = [fields componentsJoinedByString:@","];

Then, to join two lines together:

NSArray *lines = @[lineOne, lineTwo];
NSString *linesString = [lines componentsJoinedByString:@"\n"];
like image 166
Abhi Beckert Avatar answered Jan 22 '26 15:01

Abhi Beckert


Yes, you could use an NSMutableString and appendString to append to it each time.

like image 37
Joel Avatar answered Jan 22 '26 14:01

Joel