1

I am developing a tweak for iOS using Logos/Theos.

I need to store the last two characters the user has typed in at all times.

My code for this is:

static NSString *lastTwoChars = [[NSString alloc] init];
...
if (lastTwoChars.length < 2) {
    lastTwoChars = [lastTwoChars stringByAppendingString:text];
} else {
    lastTwoChars = [lastTwoChars stringByAppendingString:text];
    lastTwoChars = [lastTwoChars substringFromIndex:1];
}
...

(In this scope, text is the last character they entered in the keyboard)

This code works fine, until I press a third character. After a very long time of trial and error, I found that it is because the variable lastTwoChars is getting released, and becoming a different object.

I cannot figure out how to keep the object from being deallocated and changing to another object. I've tried to retain the variable, but either I'm doing it wrong, or that won't work.

Any help would be greatly appreciated.

Campbell Cole
  • 37
  • 1
  • 9

1 Answers1

-1

Alright. I finally figured it out. Thanks to Droppy for hinting at the problem.

I fixed it by retaining the new strings:

if (lastTwoChars.length < 2) {
    lastTwoChars = [[lastTwoChars stringByAppendingString:text] retain];
} else {
    lastTwoChars = [[lastTwoChars stringByAppendingString:text] retain];
    lastTwoChars = [[lastTwoChars substringFromIndex:1] retain];
}

I didn't know that stringByAppendingString and substringFromIndex were creating new NSString objects, so thanks again to Droppy.

EDIT: I thought this may be a memory leak, but Droppy confirmed it was.

This is my new code:

if (lastTwoChars.length < 2)
{
    lastTwoChars[lastTwoChars.length] = (unichar) text;
}
else
{
    lastTwoChars[0] = lastTwoChars[1];
    lastTwoChars[1] = (unichar) text;
}
Campbell Cole
  • 37
  • 1
  • 9