Objective-c, why can't I use the accessor method in the Init or Dealloc method

Source: Internet
Author: User

I have read Apple's official document, "Advanced Memory Management Programming," and have never understood why the accessor method cannot be used in the Init and Dealloc methods. His usual work in practice, seemingly did not find any problems. Until today, when debugging a mistake, I suddenly understood the reason.

It is not possible to use accessor in init and dealloc because we have to beware: subclasses may overwrite the accessor method of the parent class and change the behavior of the accessor method.

Reference code:

#import <Foundation/Foundation.h> @interface Test:nsobject@property (nonatomic, retain) NSString * str;@ End@implementation test-(ID) init{self    = [super init];    if (self) {        self.str = @ "AAA";    }    return self;} @end @interface test1:test@end@implementation test1-(void) Setstr: (NSString *) str{    [Super setstr: [NSString stringwithformat:@ "[%@]", str]];} @endint Main () {    @autoreleasepool {        Test *test = [[test new] autorelease];        NSLog (@ "test=%@", test.str);        Test1 *test1 = [[Test1 new] autorelease];        NSLog (@ "test1=%@", test1.str);        return 0;}    }

Output Result:

TEST=AAATEST1=[AAA]
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.