Maverick447
Maverick447

Reputation: 143

overriding property attribute in class extension

Say I have an interface

// Car.h
@interface Car 
@property ( readonly) NSInteger rpm
@end 

I want all the users of this to access this as readonly

In other areas that are private to my code and not exposed to users I want to manipulate the rpm

Say

// EngineFeedback.h
@interface EngineFeedback
@property(nonatomic , weak ) Car *theCar;
@end

// EngineFeedback.m 
-(void) engineRPMReceived:(NSInteger) newRPM
{
     theCar.rpm = newRPM;
}

How can I accomplish this (where I need this to be writeable)

Can I define a class Extension that overrides the attributes

// Car_Internal.h
@interface Car ()
@property(readwrite) NSInteger rpm 
@end 

To be able to use this as

    // EngineFeedback.m 
    #import "Car_Internal.h"
    -(void) engineRPMReceived:(NSInteger) newRPM
    {
         theCar.rpm = newRPM;
    }

Is this bad ? Is there a better way to achieve this ?

Upvotes: 1

Views: 245

Answers (1)

jlehr
jlehr

Reputation: 15597

Using a class extension to override a readonly property declaration is perfectly fine. (In fact that's the primary purpose of the readonly attribute.) However, your Car class would need to provide an implementation of setRpm: for this to work at runtime.

So given the declarations you provided, somewhere in Car.m you'd need something like this:

- (void)setRpm:(NSInteger)newRPM
{
     _rpm = newRPM;
}

Note that the class extension can be declared in EngineFeedback.m if you prefer.

Upvotes: 1

Related Questions