0

I'm having trouble trying to store input from a textfield into an array where each character is at a separate index.

I have tried storing the input as a string so I can make it all upper case and remove white spaces, but this is causing me problems too.

I figured once it is stored I could just loop through each letter and add each char to a mutable array.

Thank you for any help in advance.

  • 1
    You shouldn't do this because not every character is 1 in length. Use [stringByTrimmingCharactersInSet or stringByReplacingOccurrencesOfString](http://stackoverflow.com/questions/6608420/how-to-remove-whitespace-in-a-string) and [lowercaseString](http://stackoverflow.com/questions/8693741/converting-all-text-to-lower-case-in-objective-c/8693767#8693767). – Marcus Adams Mar 06 '13 at 15:08

2 Answers2

1

If you look at the UITextFieldDelegate you can find number of good methods from this delegate which might be useful for your tasks.

There is a method from this delegate which is called every time user press a key in UITextField

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
 //assuming dict is declared NSDictionary
 [dict setObject:[yourTextField.text stringByReplacingCharactersInRange:range withString:string] forKey:@"KEY"];
}
nsgulliver
  • 12,655
  • 23
  • 43
  • 64
  • I'm the UITextfield Delegate, how could I make that an array? –  Mar 06 '13 at 15:08
  • it is better to use `NSDictionary` that way you know the keys also `NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [dict setObject:someValue forKey:@"A-Key"];` – nsgulliver Mar 06 '13 at 15:13
  • okay I'll just try the below code first and then post my code –  Mar 06 '13 at 15:27
1
-(void)textFieldDidEndEditing:(UITextField *)textField
{
  NSString *string  = textField.text;
  NSMutableArray *theArray = [NSMutableArray array];
  for (int i = 0; i < [string length]; i++) 
  {
    [theArray addObject:[NSString stringWithFormat:@"%c",[string characterAtIndex:i]]];
  }
}

I would do the storing once the user has ended his/her editing.

lakshmen
  • 28,346
  • 66
  • 178
  • 276
  • It says error, Implicit conversion of 'unichar' (aka 'unsigned short') to id is disallowed with ARC :/ –  Mar 06 '13 at 15:30