创建仅对Objective-C中的子类可见的属性

Chr*_*ris 5 inheritance scope objective-c ios

我试图创建一个抽象类并在子类中继承它的一些属性.如果我将属性保留在抽象类的头文件中,则可以访问所有属性.问题是子类的实例也可以访问这些属性,这在我的情况下并不总是可取的.

例如,我在我的抽象类中有一个委托,它将按钮按下发送到它的子类.我意识到这可能不是构建继承的最佳方式,因此欢迎其他建议.但是,我仍然想知道我的子类如何从其超类继承一些属性而不在其实例中使所有这些属性可用.提前致谢!

以下是一些示例代码:

@interface AbstractClass : UIView

@property (nonatomic, strong) id<ButtonDelegate>buttonDelegate;

@end

…

@protocol ButtonDelegate

@required
- (void) buttonWasPressed;

@end

…

@interface SubClass() <ButtonDelegate>

- (id)init {
    self = [super init];
    if (self) {
        self.buttonDelegate = self;
    }
    return self;
}

-(void) buttonWasPressed {
    [self doSomething];
}

…

@implementation ViewController

- (void)viewDidLoad {
    SubClass *subClass = [[SubClass alloc] init];
    subClass.buttonDelegate = self; // THIS IS NOT DESIRABLE
}
Run Code Online (Sandbox Code Playgroud)

hfo*_*sli 5

做喜欢的UIGestureRecognizer事。

  1. 所有公共属性和方法都进入UIGestureRecognizer.h

  2. 所有受保护的属性和方法都进入UIGestureRecognizerSubclass.h. 仅将其导入到*.m-files 中。切勿将其包含在任何公共标头中。

  3. 所有私有属性和方法都放入*.m-files 中。使用@interface ClassName ()

示例https://gist.github.com/hfossli/8041396


Jan*_*ano 4

我的子类如何可以从其超类继承一些属性,而不在其实例中提供所有这些属性

这有什么问题吗?

#import <Foundation/Foundation.h>

@interface Animal : NSObject
{
    @protected
    NSString *name; // default access. Only visible to subclasses.
}
@end

@implementation Animal
-(NSString*)description {
    return name;
}
@end

@interface Cow : Animal
@end

@implementation Cow

-(id)init {
    self=[super init];
    if (self){
        name   = @"cow";
    }
    return self;
}
@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        Cow *cow = [Cow new];
        NSLog(@"%@", cow); // prints the name through internal access
        // error accessing from the outside: NSLog(@"%@", cow.name);

        Animal *animal = [Animal new];
        // error accessing from the outside: NSLog(@"%@", animal.name);
    }
}
Run Code Online (Sandbox Code Playgroud)

也许我误解了这个问题,你说

在 Objective-C 中创建仅对子类可见的属性

进而

问题是子类的实例也可以访问这些属性

哪一个?