Appending a string inside for loop crashes ios device - ios

I'm gathering data to an array in string format and one item is about 30 characters. When data collection is finished I try to combine all the strings into one big string, which is then written to a file. Combining strings is done inside for-loop, and it causes device to crash when number of data items gets somewhere over 4000. What is causing it and how to fix? Here's the code I have for appending strings:
NSString *content = #"";
for (int i=0; i<self.log.count; i++)
{
content = [[content stringByAppendingString:#""] stringByAppendingString:(self.log)[i]];
}

If you are trying to turn an array into a string there is an easier way to do it:
NSString *content = [self.log componentsJoinedByString:#" "];

try this...
NSString *content = #"";
for (int i=0; i<self.log.count; i++)
{
content = [[content stringByAppendingString:#""] stringByAppendingString:[NSString stringWithFormat:#"%#",(self.log)[i]]];
}

To ensure the required amount of memory is allocated, I suggest you use a mutable string with an init for the length required.
-(NSString*)concantString:(NSArray *)incomingLog {
int calculatedLength = 0;
for (int i=0; i < [incomingLog count]; i++)
{
calculatedLength += [incomingLog[i] length];
}
NSMutableString *content = [[NSMutableString alloc] initWithCapacity:calculatedLength];
for (int i=0; i < [incomingLog count]; i++)
{
content = (NSMutableString*)[[content stringByAppendingString:#""] stringByAppendingString:incomingLog[i] ] ;
}
return content;
}

Related

Copy specific index value of array to another array?

I am trying to copy a specific values at specific index from one array to another like this:
for (int i = 0; i < 100; i++) {
if ([subID[i] isEqual: #"0"]) {
NSLog(#"state : %#",arrayTempState[i]);
NSString *str = arrayTempState[i];
[arrayState addObject:str];
NSLog(#"%#",arrayState[i]);
}
arrayState is NSMutableArray and arrayTempState is NSArray
but arrayState is null every time.
I tried arrayState[i] = arrayTempState[i]; but it did not work.
arrayState was not initialised that is why it couldn't store the value.
plz try this
arrayState = [NSMutableArray array];
for (int i = 0; i < 100; i++) {
if ([subID[i] isEqual: #"0"]) {
NSLog(#"state : %#",arrayTempState[i]);
NSString *str = arrayTempState[i];
[arrayState addObject:str];
NSLog(#"%#",arrayState[i]);
}

How to add values or add object into NSArray in Objective C using for loop?

Well this is my code:
NSDictionary *dicto;
NSString *ndccode;
NSString *string=#" ";
for (int i=0; i<array.count; i++) {
dicto=[array objectAtIndex:i];
ndccode=[dicto objectForKey:#"NDCCode"];
string=[string stringByAppendingString:ndccode];
string=[string stringByAppendingString:#"\n"];
NSLog(#"%#",string);
}
NSLog(#"%#",string);
In the above code, i have values in dicto nsdictionary which loops one by one value and assigns to ndccode which is string. Then I am adding to string so that I can append it to the next line.
output :
name1
name2
name3
.....
Instead of assigning to the string. I want to assign it to an array.Could you please tell me how to assign it to an array for this example,since it is in loop. I want to use the array for later purposes.
Thank you in advance.
NSDictionary *dicto;
NSString *ndccode;
NSMutableArray *outputArray=[NSMutableArray new];
for (int i=0; i<array.count; i++) {
dicto=[array objectAtIndex:i];
ndccode=[dicto objectForKey:#"NDCCode"];
[outputArray addObject:ndccode];
}
or even more succinctly
NSArray *outputArray = [array valueForKey:#"NDCCode"];

Add text to UItextField without erasing old text

I have an UItextField, and I want to display the content of an array in it.
So I tried something like that (and then I realised it obviously wouldn't have worked):
for (NSInteger i=0; i<myArray.count; i++) {
[self.myTextField setText:myArray[i] ];
}
So, as you may guess, this code just displays the last element of my array in my text field.
My question: is it possible to edit the content of a text field, without erasing the content already present ?
Thanks a lot for your answers !
Try:
[self.myTextField setText:[[self.myTextField text] stringByAppendingString:myArray[i]]];
There are many ways to do this.
One way to do this using your existing method is
for (NSInteger i = 0; i < myArray.count; i++) {
self.myTextField.text = [NSString stringWithFormat:#"%# %#", self.myTextField.text, myArray[i]];
}
Instead of setting to your field every iteration, append the array contents to a mutable string and set the field to that string at the end. You may need to append spaces or new lines as needed if you want to format it differently.
NSMutableString *arrayContentsString = [[NSMutableString alloc] init];
for (NSInteger i = 0; i < myArray.count; i++) {
[arrayContentsString appendString:myArray[i]];
}
[self.myTextField setText:arrayContentsString];
If you just want to append text to the existing text, you can do this:
for (NSInteger i = 0; i < myArray.count; i++) {
[self.myTextField setText:[self.myTextField.text stringByAppendingString:myArray[i]]];
}
I didn't debug this so forgive me if it doesn't work.
for (NSInteger i = 0; i < myArray.count; i++) {
self.myTextField.text = [self.myTextField.text stringByAppendingString:myArray[i]];
}
NSArray has a method called componentsJoinedByString' which returns an NSString object that is the result of interposing a given separator between the elements of the array.
NSString *string = [myArray componentsJoinedByString:#" "];
[self.myTextField setText:string];
Try with fast enumeration it will be faster:-
for (NSString *str in myArray)
{
self.myTextField.text = [self.myTextField.text stringByAppendingString:str];
}
Swift answer:
self.myTextField.text = self.myTextField.text?.stringByAppendingString(" ★")

Unable to manage single elements in an NSMutableArray

So I am inserting a class object into an NSMutable array, and then I am trying to manage the specific properties of each indexed object.
Here I create the NsMutableArray:
self.currentPuzzle = [[NSMutableArray alloc]init];
for(int i = 0; i < [temp length]; i++){ //temp is a string containing #'s and dots.
AnswerSpecifier *objectToGetIntoArray = [[AnswerSpecifier alloc]init];
objectToGetIntoArray.value = [[temp substringWithRange:NSMakeRange(i, 1)] intValue];
[self.currentPuzzle addObject:objectToGetIntoArray];
}
and here I am trying to change the value property of each object. value is an int property.
for (int i = 0; i < [self.board.boardString length]; i++) {
[self.currentPuzzle objectAtIndex:i].value = [[self.board.boardString substringWithRange:NSMakeRange(i, 1)] intValue];
}
However I get an error saying that the property value was not found on object of type id. Should I just create a new array and assign it to the old one? Is there a better way to do this?
Split your code up. This makes it easier to read and debug.
for (int i = 0; i < [self.board.boardString length]; i++) {
AnswerSpecifier *answer = self.currentPuzzle[i];
NSString *boardString = [self.board.boardString substringWithRange:NSMakeRange(i, 1)];
int value = [boardString intValue];
answer.value = value;
}
You don't get points for cramming as much code as possible into one line.
But if you really just want to fix the one line you need to put the cast in the proper place:
[(AnswerSpecifier *)self.currentPuzzle[i] setValue:[[self.board.boardString substringWithRange:NSMakeRange(i, 1)] intValue]];
Try type casting the object
((AnswerSpecifier *)[self.currentPuzzle objectAtIndex:i]).value = [[self.board.boardString substringWithRange:NSMakeRange(i, 1)] intValue];
Try to replace with:
for (int i = 0; i < [self.board.boardString length]; i++) {
[[self.currentPuzzle objectAtIndex:i] setValue:[[self.board.boardString substringWithRange:NSMakeRange(i, 1)] intValue]];
}

Create string based on characters expected

I would like to create a string based on the number of characters passed in. Each character passed in will be a "X". So for example, if the length passed in is 5, then the string created should be
NSString *testString=#"XXXXX";
if it is 2 then it would be
NSString *testString=#"XX";
Can anyone tell me what the most efficient way to do this would be?
Thank you!
If you know the maximum length is some reasonable number then you could do something simple like this:
- (NSString *)xString:(NSUInteger)length {
static NSString *xs = #"XXXXXXXXXXXXXXXXXXXXXXXXXXX";
return [xs substringToIndex:length];
}
NSString *str = [self xString:5]; // str will be #"XXXXX";
If you pass in too large of a length, the app will crash - add more Xs to xs.
This approach is more efficient than building up an NSMutableString but it does make an assumption about the maximum length you might need.
- (NSString *)stringOf:(NSString *)str times:(NSInteger)count
{
NSMutableString *targ = [[NSMutableString alloc] initWithCapacity:count];
for (int i=0; i < count; i++)
{
[targ appendString:str];
}
return targ;
}
and
[self stringOf:#"X" times:4];
note that initWithCapacity: (in performance manner) better than init. But I guess that's all for efficiency.
The way I would do it is
NSMutableString *xString = [[NSMutableString alloc] init];
while ( int i = 0; i < testString.length; i++ ) {
[xString appendString:#"X"];
i++;
}
NSUInteger aLength. // assume this is the argument
NSMutableString *xStr = [NSMutableString stringWithCapacity: aLength];
for ( NSUInteger i = 0; i < aLength; i++ ) {
[xStr appendFormat:#"X"];
}
The following will do what you ask in one call:
NSString *result = [#"" stringByPaddingToLength:numberOfCharsWanted
withString:characterToRepeat
startingAtIndex:0];
where numberOfCharsWanted is an NSUInteger and characterToRepeat is an NSString containing the character.

Resources