Retain property in cocoa's objective-C

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.