I’ve been using the following code without almost any problems, but today Xcode begun to complain about it BIGTIME. I almost went nuts before I could find were the bug/memory leak indeed was. Xcode said “message sent to deallocated instance”. I commented a couple of lines (the releases) and it stopped crashing.
The thing is, I’m completely lost here… shouldn’t I release those to avoid memory leaks? I’m targeting iOS 4.0 for this project, so manual memory managment is a must.
+ (NSString*)reformatRule:(NSString*) ruleStr {
NSString *bufRule = [[[NSString alloc] init] autorelease];
NSString *buf = [[NSString alloc] init];
char c = 0;
NSString *value = [[NSString alloc] init];
for(int i=0;i<[ruleStr length];i++){
c = [ruleStr characterAtIndex:i];
if([self isCharacterOrDigit:[NSString stringWithFormat:@"%c",c]]){
buf = [buf stringByAppendingString:[NSString stringWithFormat:@"%c",c]];
}else{
DLog(@"says:%@",buf);
value = [buf stringByReplacingOccurrencesOfString:@" " withString:@""];
//[buf release];
//buf = [[NSString alloc] init];
buf = @"";
if (![value isEqualToString:@""]) {
if ([value isEqualToString:CONDITION_AND] || [value isEqualToString:CONDITION_OR]) {
bufRule = [bufRule stringByAppendingString:[NSString stringWithFormat:@"%@",value]];
}else{
bufRule = [bufRule stringByAppendingString:[NSString stringWithFormat:@"(%@)",value]];
}
}
if(c!=' '){
bufRule = [bufRule stringByAppendingString:[NSString stringWithFormat:@"%c",c]];
}
}
}
// [value release]; COMMENTED THIS LINE
// [buf release]; AND THIS ONE TOO
return bufRule;
}
This line converts
buffrom a retained pointer to an autoretained one:Similarly the
valueline a couple of lines down.If you’re not going to use ARC, you really need to understand storage management a lot better.