Coocoo4Cocoa
Coocoo4Cocoa

Reputation: 50886

Use of @synthesize/@property in Objective-C inheritance

If you have Class A with an instance var "foo" which has a @property/@synthesize directive, and Class B inherits from Class A, does it also need to @property/@synthesize "foo"? The reason I ask is because when I try to use Class B's "foo", the calling class says that "foo" is not something of a structured union or a member, which makes me believe it needs to be explicitly synthesized.

Upvotes: 12

Views: 11428

Answers (5)

Jack Mason
Jack Mason

Reputation: 1

Correct, you just declare a @property outside of the typical member variable declaration curly brackets and then @synthesize the property in the .m file. I did notice that in the child class you have use self.propertyName to reference it but in the parent class you can just use the instant variable name.

Upvotes: 0

goelectric
goelectric

Reputation: 396

Just in case this helps someone.

I came across this problem too and read these answers and still couldn't access super class variables directly. They were declared as properties and synthesized in the super class and and I had imported the header into my subclass. I was stuck until I discovered I needed to declare the member variables in the @interface section in the super class as well as a property of the superclass....! e.g.

@interface BuoyAnnotation : NSObject <MKAnnotation>
{
    CLLocationCoordinate2D coordinate;
    CLLocation* location;
    int type; 

}

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, retain) CLLocation* location;
@property (nonatomic, assign) int type;

Upvotes: 4

Georg Sch&#246;lly
Georg Sch&#246;lly

Reputation: 126165

No, you don't. Synthesized properties are added to class A and its subclasses automatically.

Upvotes: 10

Peter Hosey
Peter Hosey

Reputation: 96373

If you have Class A with an instance var "foo" which has a @property/@synthesize directive, and Class B inherits from Class A, does it also need to @property/@synthesize "foo"?

No.

The reason I ask is because when I try to use Class B's "foo", the calling class says …

No, the compiler says it.

… that "foo" is not something of a structured union or a member, which makes me believe it needs to be explicitly synthesized.

It is. In class A.

The compiler is giving you that warning because it doesn't know about the @property, which is because you have neither declared it nor imported a header that declares it. You say that class A's header declares the property, so import class A's header into class B's implementation, so that the compiler knows about the property when compiling class B.

Upvotes: 10

Andrew Grant
Andrew Grant

Reputation: 58804

WHen inheriting you should not need to redeclare any properties or variables.

Perhaps if you post your ClassB header file or a portion of then people can better pinpoint your problem.

Upvotes: 1

Related Questions