So i’m working on an application, and i’m not using automatic reference counting, so i have to do my own memory management. I have this code, which sets a value to a UIView’s layer in a first method.
Then in a second method, i retrieve it. array1 is defined in my viewDidLoad
Here is my first Method
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGFloat endLocation = [touch locationInView:self];
CGRect rect = CGRectMake(startLocation.x, startLocation.y, endLocation.x, endLocation.y);
UIView *rectstring = [[UIView alloc]initWithFrame:rect];
NSString *string = [NSString stringWithFormat:@"%d",pencilbool];
[[rectstring layer] setValue:string forKey:@"color"];
NSString *string1 = [NSString stringWithFormat:@"%f",stepper.value];
[[rectstring layer] setValue:string1 forKey:@"size234"];
[array1 addObject:rectstring];
[rectstring release];
[string release];
[string1 release];
}
Second method:
-(IBAction)secondmethod {
for (UIView *string1 in array1) {
CGContextRef gc=UIGraphicGetCurrentContext();
CGFloat width =[[string1.layer valueForKey:@"size234"] floatValue];
CGContextSetLineWidth (gc, width);
CGRect rect = [string1 frame];
CGContextMoveToPoint(gc, rect.origin.x, rect.origin.y);
CGContextAddLineToPoint(gc, rect.size.width, rect.size.height);
CGContextStrokePath(gc);
}
}
this causes an error at CGFloat width =[[string1.layer valueForKey:@"size234"] floatValue];.
However, if i remove the release calls in the first method:
[string release];
[string1 release];
It runs fine.
Why is this causing an error? Any ideas?
The non-ARC rule is to only release things that you’ve retained, explicitly or by calling such things as alloc or copy. (More exact documentation is at: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html )
stringWithFormat:returns an autoreleased object, which means you shouldn’t be adding another release.