Trying to split what the user writes in the text field, into an array full of the characters in the things he typed.
here is what I have so far
-(IBAction) generateFlashNow:(id)sender{
[textField resignFirstResponder];
NSString *string1 = textField.text;
NSString *string2 = [string1 stringByReplacingOccurrencesOfString:@"" withString:@","];
NSArray *arrayOfLetters = [string2 componentsSeparatedByString:@","];
NSLog(@"Log Array :%@", arrayOfLetters);
//NSArray *imageArray = [[NSArray alloc] init];
NSLog(@"Log First Letter of array: %@",[arrayOfLetters objectAtIndex:0]);
}
What am I doing wrong?
stringByReplacingOccurrencesOfStringis not doing anything when you pass an empty string “” sostring2is an identical copy ofstring1, hence no commas and the split operation fails.There are many ways to get this done. I can think of two:
Convert to a character array:
Or, if you only want to deal with objects, loop through each method and hand-create the array:
You could add the above logic to a method like
toArrayas a category in NSString itself, so all strings get this functionality if that’s a common case for your application. Checkout this article for more information about categories. You’d simply call[someString toArray]to get it’s array representation.