2011-04-30 119 views
30

我是iPhone开发人员的初学者。我正在尝试下面的示例程序。目标C中的构造函数C

我没有在B类中调用+(void)初始化和 - (id)init方法,而是自动调用它。

是的 - (空)intialise等于默认的构造函数在客观C.

请问[超级初始化]指向NSObject的。

如果我不使用 - (id)初始化方法,我得到一个警告,说这个类是不完整的实现。

ClassA.h

#import <Foundation/Foundation.h> 

static int ab; 

@interface ClassA : NSObject { 
    int a; 
} 

+ (void) initialize; 
- (id) init; 
- (void) displayNumOfInstance; 
- (void) disp; 

@end 

ClassA.m

#import "ClassA.h" 

@implementation ClassA 

+ (void) initialize 
{ 
    ab=0; 
} 

- (id) init 
{ 
    self = [super init]; 
    if (self!=nil) { 
     ab++; 
    } 
    return self; 
} 

- (void) displayNumOfInstance 
{ 
    NSLog(@"Number of instances of this class:%d",ab); 
} 

- (void) disp 
{ 
    NSLog(@"The value is %d",ab); 
} 

@end 

ClassB.h

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

@interface ClassB : ClassA { 

} 

- (void) display; 

@end 

ClassB.m

#import "ClassB.h" 

@implementation ClassB 

- (void) display 
{ 
    ab=20; 
    NSLog(@"The value ab is %d",ab); 
} 

@end 

class2.m

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

int main (int argc, const char * argv[]) { 
    ClassA *a = [[ClassA alloc]init]; 
    [a disp]; 
    [a release]; 

    ClassB *b = [[ClassB alloc]init]; 
    [b display]; 
    [b release]; 

    ClassA *a1 = [[ClassA alloc]init]; 
    [a1 disp]; 
    [a1 release]; 

    ClassB *b1 = [[ClassB alloc]init]; 
    [b1 display]; 
    [b1 release]; 

    return 0; 
} 

输出:

2011-04-30 15:31:42.490 class2[1674:a0f] 1 
2011-04-30 15:31:42.493 class2[1674:a0f] The value ab is 20 
2011-04-30 15:31:42.494 class2[1674:a0f] 2 
2011-04-30 15:31:42.495 class2[1674:a0f] The value ab is 20 

回答

57

默认结构通常与具有以下格式-init或在本任何变体,例如启动-initWithFrame:

方法+initialize是一个类方法(静态方法),这就是所谓的至少一次应用程序启动时。您可以使用此方法来初始化在类的所有实例中都有用的静态变量。这种方法可能对例如为一个类初始化共享缓存或共享查找映射。

对于NSObject-init方法是指定初始化,但对于其他类,这可能是不同的。 Apple使用NS_DESIGNATED_INITIALIZER宏在其类文件头中记录指定的初始化程序。例如UIView子类应该重写-initWithFrame:-initWithCoder:代替,因为这些方法都被标记为指定的初始化。

在继承和实现自定义指定初始化,不要忘了初始化超类为好。让我们具有例如UIView子类具有自定义指定初始化-initWithFrame:title:

:对正在初始化可以在苹果开发者网站上找到

// A custom designated initializer for an UIView subclass. 
- (id)initWithFrame:(CGRect)frame title:(NSString *)title 
{ 
    // Initialize the superclass first. 
    // 
    // Make sure initialization was successful by making sure 
    // an instance was returned. If initialization fails, e.g. 
    // because we run out of memory, the returned value would 
    // be nil. 
    self = [super initWithFrame:frame]; 
    if (self) 
    { 
     // Superclass successfully initialized. 
     self.titleLabel.text = title 
    } 
    return self; 
} 

// Override the designated initializer from the superclass to 
// make sure the new designated initializer from this class is 
// used instead. 
- (id)initWithFrame:(CGRect)frame 
{ 
    return [[self alloc] initWithFrame:frame title:@"Untitled"]; 
} 

更多细节:我们可以按如下方式实现它