我要檢查,如果一個子類的以下實現是正確的目標C.超類初始化
首先代碼父父寫的Objective C的子類:
#import "Employee.h"
@implementation Employee
-(id)init
{
return [self initEmployee:(NSString *)@"" withId:(NSString *)0];
}
-(id)initEmployee:(NSString *)theName withId:(NSString *)theId
{
self = [super init];
if (self) {
_name = theName;
_EmpId = theId;
}
return self;
}
@end
然後子類。
#import "FullTimeEmp.h"
@implementation FullTimeEmp
-(id)init
{
return [self initEmployee:(NSString *)@""
withId:(NSString *)@""
andSalary:(NSNumber *)0
withBonus:(NSNumber *)0];
}
-(id)initEmployee:(NSString *)theName
withId:(NSString *)theId
andSalary:(NSNumber *)theSalary
withBonus:(NSNumber *)theBonus
{
self = [super initEmployee:(NSString *)theName withId:(NSString *)theId];
if (self) {
self.salary = theSalary;
self.bonus = theBonus;
}
return self;
}
@end
這運行正常,但我一直沒能確認這是做了正確的方式,使用:
自我= [超級initEmployee:(的NSString *)theName withId:(的NSString * )theId];
在繼承超類部分(Name和ID),然後是子類部分的子類中,指定組成Full Time Employee對象的子類添加(Salary和Bonus)。
我讀過所有關於我們使用自己的理由= [超級初始化],但已很難找到如何在子類的初始化是在我的書我還是在網上編碼很好的例子。
**爲什麼**哦,爲什麼所有這些多餘的,醜陋的,不可讀的,不正確的演員? :((((( – 2014-01-26 21:15:33
請閱讀[* Cocoa的編碼指南:命名方法*](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html)。Better名字是'initWithName:employeeId:'和'initWithName:employeeId:salary:bonus:'。 –