Objective-C 2.0: Inheriting Synthesized Instance Variables

I have the following code:

// ClassA.h
@interface ClassA : NSObject 
@property (nonatomic, retain, readonly) id my_property;
@end

// ClassA.m
@implementation ClassA
@synthesize my_property;
- (id)init {
    if (self = [super init]) {
        self->my_property = [NSNumber numberWithInt:1];
    }
    return self;
}

- (void)debug {
    NSLog(@"%@", self->my_property);
}
@end

// ClassB.h
#import "ClassA.h"

@interface ClassB : ClassA 
@end

// ClassB.m
#import "ClassB.h"

@implementation ClassB
@synthesize my_property;
- (id)init {
    if (self = [super init]) {
        self->my_property = [NSNumber numberWithInt:2];
    }
    return self;
}
@end

I call the above code like this:

ClassB *b = [[ClassB alloc] init];
[b debug];

Output signal 1. If I use the method -[Class A debug]to use self.my_property, the output will be 2.

My (limited) understanding is that with the “modern” Objective-C development environment, ivars class generates dynamically. Can subclasses of classes with these dynamically generated ivars access the specified instance variables? If I do not include the line @synthesize my_propertyin ClassB.m, the compiler will give me an error:

error: 'struct ClassB' does not have a name named 'my_property'

, -[ClassB init], , ivar, , - , . , API?

. , . , @interface , . SO:

, , , , , .

+3
3

, ivar ClassA.h, , . @synthesize ClassB.m, ivar , .

+2

@private. . , . , .

+1

, my_property, A , my_property. .

// ClassA.h
@interface ClassA : NSObject 
@property (nonatomic, retain, readonly) id my_property;

// designated initialiser
-(id) initWithMyProperty: (NSNumber*) newMyProperty;

@end

// ClassA.m
@implementation ClassA
@synthesize my_property;

- (id)initWithMyProperty: (NSNumber*) newMyProperty 
{
    if (self = [super init]) 
    {
        my_property = [newMyProperty retain];
    }
    return self;
}

-(id) init
{
    return [self initWithMyProperty: [NSNumber numberWithInt: 1]];
}

-(void) dealloc
{
    [my_property release];
    [super dealloc];
}

...

@end

// ClassB.m
#import "ClassB.h"

@implementation ClassB
- (id)init 
{
    if (self = [super initWithMyProperty: [NSNumber numberWithInt:2]]) 
    {
        // Any other initialisation
    }
    return self;
}

@end
0

Source: https://habr.com/ru/post/1790637/


All Articles