Essentially, I am making an app that allows the user to type in chemistry formulas using a custom keyboard.
The keyboard will have several keys, for example, "Na", "H", and "O". Pressing them in different combinations will result in different formulas. For example, Na + O will result in NaO. Pressing any key consecutively will increase the subscript of that given element. For example, H + H + O will result in H2O.
The code below determines how the textfield combines the different elements to make the formulas. I'm wondering if it's too confusing. Also, I'm not sure if I'm correctly managing the memory.
consecutiveElementCount = 0;
formula = [[NSMutableString stringWithString:@""] retain]; // released in dealloc
^^^ declared in the init
method.
- (void)addElement:(NSString *)currentElement {
if (![currentElement isEqualToString:lastElementPressed]) {
// when new element is pressed
[formula appendString:currentElement];
lastElementPressed = currentElement;
consecutiveElementCount = 1;
}
else if ([currentElement isEqualToString:lastElementPressed]) {
// when element is pressed consecutively
if (consecutiveElementCount == 1) {
// since there is no '1' subscript, nothing needs to be deleted
[formula appendString:@"₂"];
subscriptLength = 1;
}
if (consecutiveElementCount > 1) {
// deletes last subscript and replaces it with new subscript
NSArray *subscriptList = [[[NSArray alloc] initWithObjects:@"₂", @"₃", @"₄", @"₅", @"₆", @"₇", @"₈", @"₉", @"₁₀", @"₁₁", @"₁₂", nil] autorelease];
NSRange range = NSMakeRange (([formula length] - subscriptLength), subscriptLength);
[formula deleteCharactersInRange:range];
NSString *tempSubscript = [[subscriptList objectAtIndex:consecutiveElementCount - 1] autorelease];
[formula appendString:tempSubscript];
subscriptLength = [tempSubscript length];
}
// don't increase subscript after 12
if (consecutiveElementCount < 11)
consecutiveElementCount ++;
}
NSLog(@"%@", formula);
}