topgun
topgun

Reputation: 2573

Require some understanding for Singleton Pattern

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.

Upvotes: 2

Views: 97

Answers (3)

Bastian
Bastian

Reputation: 10433

when you call self.enteredCode = XXX it will call [self setEnteredCode:XXX]. Since you are using a retain property this will release the old value of enteredCode, and retain the new value.

if you directly manipulate the enteredCode variable you will have memleaks and crashes because it will try to release something that is not retained later.

Upvotes: 1

bryanmac
bryanmac

Reputation: 39296

If I understand correctly, self.enteredCode works but enteredCode fails.

If that's the case then I believe it's because you're bypassing the property and setting the iVar directly. That means you're assigned an auto released object and bypassing the retain mechanism.

Consider using something like _enteredCode for your iVars do it's clearer in your code when you're bypassing properties.

Upvotes: 0

Simon Lee
Simon Lee

Reputation: 22334

This is not to do with singletons. When you do self.enteredCode you are going through the property which is set to 'retain'. The stringByAppendingString method 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.

Upvotes: 3

Related Questions