Add text to UItextField without erasing old text - ios

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(" ★")

Related

Loading NSMutableArray objects into an IBCollection of Labels

My problem is that when I use fast enumeration to load objects from my array, like so:
for(SetOfObjects *set in _myArray){
NSLog (#"%#"[set anObject];
}
It will print out my specified object without a problem, however when it comes time to assign these objects to an NSArray of labels. The last object returns as 0.
Like so:
for(SetOfObjects *set in _myArray){
for(UILabel *label in _arrayOfLabels){
int i = [set intObject];
NSString *string = [NSString stringWithFormat:#"%i",i];
label.text = string;
}
}
I think, I have gone wrong here. The code works, but the problem is that all labels are then set as 0.
Any tips welcome.
You are iterating the labels within each SetOfObjects instance, when in fact you want to iterate both arrays at the same time, which cannot be done using fast enumeration.
Instead revert to indexed-access of both arrays:
NSInteger count = [_myArray count];
NSAssert([_arrayOfLabels count] == count, #"Different array sizes!");
for (NSInteger index = 0; index < count; index++) {
SetOfObjects *set = _myArray[index];
UILabel *label = _arrayOfLabels[index];
int i = [set intObject];
NSString *string = [NSString stringWithFormat:#"%i",i];
label.text = string;
}
Note the assertion to check that both arrays are the same size.
EDIT: Oops, i was a bad variable name to choose for the index...

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]];
}

UITextfield text in array will not change a label's text in another array

Please help. What am I doing wrong? textfield.text goes into one array and is suppose to change a label that belongs to another array.
I have multiple textfields. Im trying to save the text of each field to an array and then setAlpha to 0. Then I have an equal amount of labels that I want to change to the textfield's text. I have tried using mutable and immutable arrays. I keep getting errors.
I've tried multiple ways and its got to be something simply dumb I'm missing. I've greatly reduced these arrays just to post here.
_namesText = [NSMutableArray arrayWithObjects:_nameLabel1.text, _nameLabel2.text, nil];
_names = [NSMutableArray arrayWithObjects:_nameLabel1, _nameLabel2, nil];
_nameInputs = [NSMutableArray arrayWithObjects:_p1NameTextField, _p2NameTextField, nil];
_playerNameText = [NSArray arrayWithObjects:_p1NameTextField.text, _p2NameTextField.text, nil];
enter code here
- (IBAction)enterNamesButton:(id)sender {
//These don't work.
for (int i = 0; i < _numberOfPlayers; i++) {
[_names[i] setAlpha:1];
NSString *tempString = [[NSString alloc]initWithString:[_nameInputs[i] text]];
[_lastTry addObject:tempString];
}
//Then tried this. This is after trying for 2.5 hours and different coding.
for (int i = 0; i < _numberOfPlayers; i++) {
_namesText[i] = _lastTry[i];
UILabel *cell = [[UILabel alloc] init];
cell.text = _lastTry[i];
//[[_namesText[i] textLabel] text] = #"Idiot";
_namesText[i] = cell;
NSLog(#"%#", _namesText[i]);
// This works (but bad practice) and I want to loop through arrays that each UI element belongs to instead of typing it all out.
// _nameLabel1.text = _p1NameTextField.text;
// _nameLabel2.text = _p2NameTextField.text;
I expect this to work but NOPE!!!!
Assuming the following:
Array _fromTextField is the textfield you want to copy from and set Alpha to 0
Array _toLabelField is the label you want the text to appear in
Array _toStoreStrings is where you keep all the strings, for later maybe ?
NSMutableArray *_fromTextField = [[NSMutableArray alloc] init]; // Put the Text Fields in Here
NSMutableArray *_toLabelField = [[NSMutableArray alloc] init]; // Put the Labels in Here
NSMutableArray *_toStoreStrings = [[NSMutableArray alloc] init];
int count = 0;
int overRun = [_toLabelField count];
for (UITextField *tf in _fromTextField)
{
tf.alpha = 0;
NSString *tempString = [[NSString alloc]initWithString:tf.text];
[_toStoreStrings addObject:tempString];
if (count < overRun) // Check just in case Array sizes not same
{
UILabel *lb = [_toLabelField ObjectAtIndex:count];
lb.text = tempString;
}
else
break;
count++;
}
The issue your code faces is you have an array of NSObject. The compiler has no idea they are UITextField or UILabel unless you cast them with (type_cast *) or point a new typed variable at them. Hence the crashes you were seeing.
I would do it this way:
for (int i = 0; i < _numberOfPlayers; i++) {
_namesText[i] = _lastTry[i];
}
I cannot see why this won't work... does it?

Appending a string inside for loop crashes ios device

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;
}

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