@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私有属性:@interface MyBaseClass ()@property (nonatomic,retain) NSObject *someObject;@end
然后,您可以在MyBaseClass和MySubclass中自由声明该声明。这让MySubclass知道这些属性,以便它的代码可以谈论它们。
如果重复打扰你,将类扩展名放在自己的.h文件中,并将其导入两个.m文件。
我会给自己的代码一个例子。这里是MyDownloaderPrivatePropertIEs.h:
@interface MyDownloader ()@property (nonatomic,strong,reaDWrite) NSURLConnection* connection;@property (nonatomic,copy,reaDWrite) NSURLRequest* request;@property (nonatomic,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)。子类可以访问由超类合成其访问器的私有属性。我相信这是你想要完成的第一个地方。
总结以上是内存溢出为你收集整理的Objective-C:如何从子类访问父属性?全部内容,希望文章能够帮你解决Objective-C:如何从子类访问父属性?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)