Objective-C:如何从子类访问父属性?

标签 objective-c cocoa-touch cocoa oop

如果我定义了这个类,如何访问子类中的 someObject 属性而不会出现编译器错误?

@interface MyBaseClass
  // someObject property not declared here because I want it to be scoped 
  // protected. Only this class instance and subclass instances should be
  // able to see the someObject property.
@end

// This is a private interface extension...properties declared here
// won't be visible to subclasses. However, I don't see any way to 
// declare protected properties...
@interface MyBaseClass (private)
   @property (nonatomic, readwrite, retain) NSObject *someObject;
@end

@interface MySubclass : MyBaseClass 
@end

@implementation MySubclass

- (id) init {
    // Try to do something with the super classes' someObject property. 
    // Always throws compile errors.

    // Semantic Issue: Property 'someObject' not found 
    // object of type 'MySubclass *'
    self.someObject = nil; 

}
@end



我显然不明白继承是如何在objective-c中工作的。有人可以启发我吗?

最佳答案

您需要的解决方案是在类扩展中声明 MyBaseClass 私有(private)属性:

@interface MyBaseClass ()
@property (nonatomic, readwrite, retain) NSObject *someObject;
@end

然后您可以自由地在 MyBaseClass 在 MySubclass 中作出该声明both。这让 MySubclass 知道这些属性,以便它的代码可以讨论它们。

如果重复困扰您,请将类扩展名放在自己的 .h 文件中,然后将其导入到两个 .m 文件中。

我将从我自己的代码中举一个例子。这是MyDownloaderPrivateProperties.h:

@interface MyDownloader ()
@property (nonatomic, strong, readwrite) NSURLConnection* connection;
@property (nonatomic, copy, readwrite) NSURLRequest* request;
@property (nonatomic, strong, readwrite) NSMutableData* mutableReceivedData;
@end

没有对应的.m 文件,仅此而已;可以说,它是纯粹的声明性的。现在是 MyDownloader.m 的开始:

#import "MyDownloader.h"
#import "MyDownloaderPrivateProperties.h"
@implementation MyDownloader
@synthesize connection=_connection;
@synthesize request=_request;
@synthesize mutableReceivedData=_mutableReceivedData;
// ...

这是它的子类MyImageDownloader.m的开始:

#import "MyImageDownloader.h"
#import "MyDownloaderPrivateProperties.h"

问题解决了。隐私被保留,因为这些是唯一导入 MyDownloaderPrivateProperties.h 的类,所以就编译器而言,它们是唯一知道这些属性的类(这就是隐私在 Objective- C)。子类可以访问其访问器由父类(super class)合成的私有(private)属性。我相信这就是您最初想要实现的目标。

关于Objective-C:如何从子类访问父属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5588799/

相关文章:

View 中的 iOS 静态表?

ios - Apptimize\Optimizely 如何在 iOS 上运行?

ios - 当 UITableView 嵌入到 UIPageViewController 中时,如何使用 hidesBarsOnSwipe 隐藏 NavigationBar?

macos - 使 NSTableView 单元格只能以编程方式编辑

ios - UIPickerView 在 UITableView 中使用 DateCell

objective-c - local、global、static、auto、register、extern、const 和 volatile 变量存储在哪里?

ios - UITableview 在标题部分上方添加空间

ios - 我什么时候可以开始使用通过 UIAppearance 设置的属性?

ios - float 自动布局 iOS/OSX

cocoa - 同步架构版本控制