當前位置:成語大全網 - 書法字典 - ios的懶加載和設置方法可以用self嗎?

ios的懶加載和設置方法可以用self嗎?

在編程中,我們經常會用到懶加載,顧名思義,就是在使用的時候,我們會在實現數據源方法的時候,打開空間,比如iOS開發中最常用的控件UITableView。通常我們寫objective-c-(nsinteger)table view:(uitableview *)table view number of row insertion:(nsinteger)section { return self。dataarray.count}-(uitableviewcell *)table view:(uitableview *)table view cell for rowatindexpath:(nsindexpath *)index path {//1。get cell xwshopcell * cell =[xwshopcell with table view:table view];//2.傳輸模型cell . wine = self . data array[index path . row];//3.返回單元格返回單元格;}上面的代碼中,返回self . data array . count;其實就是用@ property(非原子,強)nsarray * dataarray@property的特性為屬性生成get和set方法,這裏是被調用的get方法,但是在上面的代碼中,return self.dataArray.count會調用-(nsarray *)dataarray { return _ dataarray }。如果成員屬性dataArray壹開始沒有賦值,那麽在使用的時候,不重寫就會給出錯誤和空指針,所以壹般我們會重寫get方法//重寫get方法-(nsarray *)dataArray { if(nil = = _ dataArray){ _ dataArray =[nsarray];} return _dataArray}這種寫入會阻止成員屬性被賦值。綜上,Objective-C的懶加載其實是調用成員屬性的get方法來初始化值,而Swift的懶加載,則是Swift//MARK tabview的dataSource代理方法func table view(table view:UITableView,numberofroweinsertion section:Int)不同於Objective-C-> Int { return self . data array . count } func table view(table view:UITableView,cellforrowatdinexpath indexPath:NSIndexPath)-& gt;UITableViewCell{ //1。Get celllet cell = xwshopcell。cellwithtableview(table view)//2。轉移模型單元格。酒=自我。dataarray [indexpath。row]//3。Return cell return cell}和Swift中存儲的這個return self.dataArray.count的屬性必須初始化,類型必須確認,也可以使用可選類型。總之要確認類型,畢竟Swfit是壹種類型安全的語言,所以Swift提出了lazy屬性,用法//1。分析NSArray是閉包的返回值。而這是壹個無參數閉包lazy var data array:ns array = {[]}()/2。也可以寫成lazy var data array:nsarray = { return nsarray()}()/3。加載LazyVar數據數組:數組