James Skidmore
James Skidmore

Reputation: 50308

How does adding a variable as a property affect it?

What difference does it make in memory management to define a variable as a property? For instance:

@interface foo {
  NSString *theStr;
}
@end

@implementation foo
- (void)bar {
  NSLog(theStr);
}
@end

Versus:

@interface foo {
  NSString *theStr;
}
@property(retain) NSString *theStr;
@end

@implementation foo
@synthesize theStr;
- (void)bar {
  NSLog(theStr);
}
@end

It seems like the first is autoreleased or something similar, while the second is retained throughout the life of the class. Is that the case, or what is the difference?

Upvotes: 0

Views: 47

Answers (2)

El Developer
El Developer

Reputation: 3346

I don't think the first case shows an autoreleased object, it would all depend on how you managed the creation and the destruction of that particular object. If for instance when you create that object you call:

//This string will indeed be autoreleased
theStr=[NSString stringWithString:@"Jibber jabber"];

//Or even
theStr=@"Jibber jabber";

But you have to take charge of the memory management if you create it in the following way:

//Manage my memory
theStr=[[NSString alloc] init];

//You have to release this property on the dealloc method
-(void)dealloc{
    [theStr release];
    [super dealloc];
}

On your second example, you create a setter and a getter method for the property theStr and by adding the nonatomic attribute, you make your property not thread safety, meaning that a thread can begin to modify your property while another one is already editing it. And by setting the retain attribute to your property, the setter method will be synthesized the following way:

- (void) setTheStr:(NSString *) newString {
    [newString retain]; 
    [theStr release]; 
    theStr = newSupervisor; 
}

You can consult more about this in one of my favorite books, Learning Objective-C 2.0 in chapter 12.

Upvotes: 1

Adrian Schönig
Adrian Schönig

Reputation: 1786

If you define a variable just in the interface without defining it as a property (as in your first example) means that you'll have to take care of everything related to memory management yourself. Assigning something to that variable will not retain it automatically, not will setting the variable to something else release the previous value.

Defining it as a property creates getter and setter methods under the hood. Most importantly, if you use it with the "retain" keyword, your setter method will retain the new value (and release the old one if there was one).

Note that the setter method will only be invoked if you use the dot notation, e.g., self.myStr = @"new string", or the method call, e.g., [self setMyStr:@"new string"]. If you just call myStr = @"new string" the setter method will not be called and you need to release the old value yourself and retain the new one.

Upvotes: 1

Related Questions