初始化方法,init,构造器

1.继承于NSObject

 1 class student: NSObject {
 2     
 3     var name : String?
 4     var age : Int = 0
 5     var friend : Int = 0
 6     
 7     init(name : String , age : Int , friend : Int) {
 8         super.init()
 9         self.name = name
10         self.age = age
11         self.friend = friend
12     }
13     
14     init(dict : [String : AnyObject]) {
15         super.init()
16         setValuesForKeys(dict)
17     }
18     
19 }

2.继承于UIView

(1)系统默认初始化方法

class LyContentView: UIView {

    //系统默认初始化方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //操作在这实现
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

(2)自定义初始化方法

注意:自定义初始化方法读是调用 super.init(frame: frame),而不是super.init()

class LyContentView: UIView {

    fileprivate var name : String?
    fileprivate var age : Int
    
    init(frame: CGRect , name : String , age : Int) {
        self.name = name
        self.age = age
        //这里必须用init(frame:,而不是init
        super.init(frame: frame)
        
        //操作在这实现
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

3.UITableViewCell

import UIKit
//cell的标识
let ID = "LyTableViewCell"

class LyTableViewCell: UITableViewCell {

    class func cellWithTableView(_ tableView : UITableView) -> LyTableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: ID) as? LyTableViewCell
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: ID) as? LyTableViewCell
        }
        return cell!
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        //添加控件,一次性属性读在这实现
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

4.UICollectionViewCell

import UIKit
//cell的标识
private let ID = "LyCollectionViewCell"

class LyCollectionViewCell: UICollectionViewCell {
    
    class func cellWithCollectionView(_ collectionView : UICollectionView , indexPath : IndexPath) -> LyCollectionViewCell {
        collectionView.register(LyCollectionViewCell.self, forCellWithReuseIdentifier: ID)
        return collectionView.dequeueReusableCell(withReuseIdentifier: ID, for: indexPath) as! LyCollectionViewCell
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

 5.便利构造器

extension UIColor {
    
    /* 类似于oc中的category/分类
     1.convenience
     2.最后别忘了调用自己一个默认的初始化方法self.init(....
     */
    
    convenience init(r : CGFloat, g : CGFloat, b : CGFloat) {
        self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0)
    }
}

6.构造方法规则

/*
 规则 1 :如果子类没有定义任何指定构造器,它将自动继承所有父类的指定构造器。
 规则 2 :如果子类提供了所有父类指定构造器的实现——无论是通过规则 1 继承过来的,还是提供了自定义实现——它将 自动继承所有父类的便利构造器。
 即使你在子类中添加了更多的便利构造器,这两条规则仍然适用
 */
class Food {
    var name: String
    init(name: String) {
        self.name = name
    }
    convenience init() {
        self.init(name: "[Unnamed]")
    }
}

/*
 1.如果RecipeIngredient没有提供任何构造方法,那么它定义的属性必须给初始值,它默认继承Food的构造方法
 */
class RecipeIngredient: Food {
    var quantity: Int = 0
    init(name: String, quantity: Int) {
        self.quantity = quantity
        super.init(name: name)
    }
    override convenience init(name: String) {
        self.init(name: name, quantity: 1)
    }
}

let oneMysteryItem = RecipeIngredient()
oneMysteryItem.quantity

let oneBacon = RecipeIngredient(name: "Bacon")
let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6)

7.可失败构造器

/*
 1.在init后面+ ?
 2.注意 :可失败构造器的参数名和参数类型,不能与其它非可失败构造器的参数名,及其参数类型相同。
 3.注意 :成功不需要return
 */
struct Animal {
    let species: String
    init?(species: String) {
        if species.isEmpty { return nil }
        self.species = species
    }
}

class Person : NSObject {
    var name : String?
    var age  : Int
    
    init?(age : Int) {
        if age < 0 { return nil }
        self.age = age
        
        super.init()
    }
    
    init(name : String , age : Int) {
        self.name = name
        self.age = age
        super.init()
    }
}

let p = Person(age: -1)//这里p为nil
p?.age

8.使用kvo,dict -> model

class Person: NSObject {
    
    //1.要设置为可选类型,要不就设置初始值
    var name : String?
    var age  : Int = 0
    
    init(dict : [String : AnyObject]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forKeyPath keyPath: String) {
        super.setValue(value, forKeyPath: keyPath)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
}

 

posted @ 2017-03-27 14:12  ZJea  阅读(1856)  评论(0编辑  收藏  举报