Objective-C:访问继承类中的私有属性

Len*_*sen 7 inheritance properties private objective-c

我正在尝试访问继承类的私有属性.那可能与苹果给我的命名惯例有关吗?

标题:

#import <Foundation/Foundation.h>

@interface FooBar : NSObject
-(void)doSomeThingWithThisNumber:(NSInteger)aNumber;
@end
Run Code Online (Sandbox Code Playgroud)

执行:

#import "FooBar.h"


@interface FooBar()
@property NSInteger myPrivateFoo;
@end


@implementation FooBar
@synthesize myPrivateFoo = _myPrivateFoo;

-(void)doSomeThingWithThisNumber:(NSInteger)aNumber
{
    _myPrivateFoo = aNumber;
}

@end
Run Code Online (Sandbox Code Playgroud)

如果我将这个类继承到一个我无法访问的新类_myPrivateFoo.还有另一种方法来代替头文件中的声明吗?

Ale*_*hol 16

在子类的实现中,只需将私有类声明放在主@interface之前.这将防止编译错误,因为编译器将知道该属性存在.这就是我所说的"私人类别声明":

@interface FooBar()
@property NSInteger myPrivateFoo;
@end
Run Code Online (Sandbox Code Playgroud)