I am going to paste a code here and had a question regarding that which I wanted to understand merely, based on the logical way.
@interface MySingleton : NSObject {
NSString *enteredCode;
}
@property (nonatomic, retain) NSString *enteredCode;
@end
@synthesize enteredCode;
-(void) addInput:(NSString *) input
{
self.enteredCode = [self.enteredCode stringByAppendingString:input];
}
- (void)dealloc {
[enteredCode release];
}
@end
In my code, if I utilize “self.enteredCode = [self.enteredCode stringByAppendingString:input];”
everything works fine but “enteredCode = [self.enteredCode stringByAppendingString:input];” it gets exc_bad_access, and I am just wondering why this case be?
I am just trying to understand what difference really does it makes without having self there?
Thanks.
This is not to do with singletons. When you do
self.enteredCodeyou are going through the property which is set to ‘retain’. ThestringByAppendingStringmethod is a convenience method with returns an autoreleased object to you, meaning that it will be released at some point on the next run loop. You need to retain this value to stop it being released, which is fine when you assign it through the property as it is properly retained by you and you can use it as you like.When you reference the variable directory (without the
self.) you bypass this and as such you don’t ever retain the value, the value is subsequently released and you reference bad memory and BOOOOOOOOM, bad access.