iPhone Super / SubClass示例

时间:2011-07-18 19:13:54

标签: objective-c xcode inheritance

我有一个超类问题:

import <Foundation/Foundation.h>
#import "Answer.h"

@interface Question : NSObject {
    NSString* qId;
    NSString* qTitle;
    NSString* qNumber;  
    NSString* sectionId;
    NSString* type;
    Answer* answer;
}

@property (nonatomic, retain) NSString* qId;
@property (nonatomic, retain) NSString* qTitle;
@property (nonatomic, retain) NSString* qNumber;
@property (nonatomic, retain) NSString* sectionId;
@property (nonatomic, retain) NSString* type;
@property (nonatomic, retain) Answer* answer;

@end


#import "Question.h"

@implementation Question
@synthesize qId, qTitle, qNumber, sectionId, type, answer;

-(id)init
{
    if (self = [super init])
    {
        // Initialization code here
        answer = [[Answer alloc]init];
    }
    return self;
}

-(void) dealloc{
    [answer release];
    [super dealloc];
}

@end

我有几种类型的问题,一个例子是滑块问题。我希望这个类继承问题:

#import <Foundation/Foundation.h>
#import "Question.h"

@interface SliderQuestion : Question {
    (NSString*) min;
    (NSString*) max;
}

@property (nonatomic, retain) NSString* min;
@property (nonatomic, retain) NSString* max;

@end
}

#import "SliderQuestion.h"

@implementation SliderQuestion

@synthesize min, max;

@end

这是子类的正确方法吗? SliderQuestion会继承Question中包含的属性吗?

SliderQuestion* s = [[SliderQuestion alloc]init];
NSLog(@"%@", s.qId); //is this valid

2 个答案:

答案 0 :(得分:2)

您真的希望minmax成为NSString的实例吗? float似乎更合适。

另外,请废弃()中的(NSString *)以删除警告/错误消息。

最后,这是子类的适当方式。 SliderQuestion的实例将继承Question类的所有属性和方法(以及NSObject

答案 1 :(得分:0)

注意NSStrings周围的(和),你可能想要删除它们。