Visibility of properties in Class Extensions and inheritance in Objective C

北慕城南 提交于 2019-12-10 12:47:55

问题


Say I have 2 classes: Money and Dollar, where Dollar inherits from Money.

Money has a property declared in a class extension:

#import "Money.h"

@interface Money ()
@property(nonatomic) NSUInteger amount;
@end

@implementation Money

@end

Dollar inherits this property, but it's not visible from methods in Dollar. I can "fix", by redeclaring the property in Dollar.m:

@interface Dollar ()
@property(nonatomic) NSUInteger amount;
@end
@implementation Dollar


}
@end

I really dislike this and I'm not even sure that I know what the compiler is doing:

  1. Is it just making the property visible?
  2. Is it creating a new property and new iVar and "shadowing" the previous one?

What's the best way to have a property hidden from everyone except the implementation of the class and its subclasses?

Ideally, I would not like amount to be visible in the .h file, as it's an implementation detail.


回答1:


In answer to the first question, probably the first option. Its just smooshing everything together for Money at compile time. Compilers and Pre-Compilers are clever.

You can use private headers to accomplish what you are trying to do

A public header file Money.h

//Money.h 
@interface Money : NSObject
//public decl 
@end

A private header file for subclasses Money-Private.h

//Money-Private.h
@interface Money ()
@property(nonatomic) NSUInteger amount;
@end

Which is used by the implementation of Money and any subclasses or categories e.g

The public face of dollar Dollar.h

#import "Money.h"
@interface Dollar:Money
@end

and the implementation Dollar.m

#import "Money-Private.h"
@implementation Dollar

-(void)foo
{
    self.amount = 75;
}

@end

Should you ever choose to create a public framework then make sure only the public headers get copied into the bundle.



来源:https://stackoverflow.com/questions/17192443/visibility-of-properties-in-class-extensions-and-inheritance-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!