If you define a retain property in an objective-C class, only obj. the attribute takes effect only when accessed in the form of VaR, that is, the getter/setter method of the member variable is used. Otherwise, the attribute cannot take effect. For example:
#import <Foundation/Foundation.h>@interface MyController : NSObject{ NSString *ms;}@property(retain) NSString *ms;- (IBAction)buttonPressed:(id)sender;@end
We first use the access attribute method to access the MS member variable:
#import "MyController.h"@implementation MyController@synthesize ms;- (id)init{ self = [super init]; if (self) { // Initialization code here. } return self;}- (IBAction)buttonPressed:(id)sender{ NSString *s = [[NSString alloc] initWithFormat:@"Hello"]; self.ms = s; [s release]; NSLog(@"The content is: %@", ms);}@end
This program will be executed very normally. Although S is assigned to self. the release method is called after ms, but because of self. the attribute of MS is retain, so the reference count of S String object is added to 1, so that this object is retained.
If we change row 23rd:
ms = s;
Then the program will crash when it is executed to nslog. Because the setter method of MS is not used here, the retain attribute does not take effect. At this time, S has been released, so Ms points to an invalid object.