初始化方法的实现

    Objective-C,初始化方法的实现需要遵守比其它 种类方法更多的约束和规则:

    自定义初始化方法的命名一般应以 “init”开头

    id

    初始化方法的返回值类型必须是 id

    在自定义初始化方法的实现中,必须有对本类的定初始化方法的引用

    

    初始化方法的实现 在实现中引用其它初始化方法时,注意把返回值赋给 self

    在对实例变量赋值时,进行直接访问,而不是透过 访问器 self,如果初始化过程失败,则返回 nil



    下面是一个简单的对方法进行复写的例子:

    - (id)init { 
        // Assign self to value returned by super's designated initializer // Designated initializer for NSObject is init 
        if (self = [super init]) {
    
            creationDate = [[NSDate alloc] init];
            
            return self;
        
        }
    
        return nil;
    
    }


    初始化方法不必对所有的变量都一一赋值


    下面是使用一个传入参数来进行初始化的初始化方法的例子:

    - (id)initWithImage:(NSImage *)anImage { // Find the size for the new instance from the p_w_picpath
    
        NSSize size = anImage.size; 
    
        NSRect frame = NSMakeRect(0.00.0, size.width, size.height); 
        // Assign self to value returned by super's designated initializer 
        // Designated initializer for NSView is initWithFrame: 
        if (self = [super initWithFrame:frame]) {
    
            p_w_picpath = [anImage retain]; 
        
            return self;
    
        }

    }

    处理初始化失败

    Handling Initialization Failure

    通常情况下,如果在初始化过程中发生任何异常,

    应当调用[self release]并返回 nil
     
    使用这种机制会带来以下的两个关联结果:
     
     
     
    任何收到 nil
     
    作为返回值的对象都能够很好地对它进行处理,但是如果它在那之前已经为新对象设置了外部连接关系,则还需要对这些连接关系进行清理
     
     
     
    对象的 dealloc 

    方法必须能保证能够处理初始化不完全的对象
     
    通常应当在完成对先期初始化结果的检查后才进行外部连接 的建立:
     
    - (id)init { 
         
         if (self = [super init]) {
    
          creationDate = [[NSDate alloc] init]; 
         
            return self;
    
        }
         
     
     
     这个例子展示了初始化方法如何处理未正常传入的参数      
     NSRect frame = NSMakeRect(0.0,0.0, size.width, size.height); 
     - (id)initWithImage:(NSImage *)anImage { 
         //super's designated initializer 
         if (anImage == nil) {  
         
         [self release]; 
        
             return nil;
         }
         
          // Designated initializer for NSViewis initWithFrame:
         
         if (self = [super initWithFrame:frame]) {
         
             p_w_picpath = [anImage retain]; 
             
             // Find the size for the new instance from the p_w_picpath
             
             NSSize size = anImage.size;
             
             return self;
         }
         
    }