版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
【移動應用開發(fā)技術】iOS中如何創(chuàng)建Model
在下給大家分享一下iOS中如何創(chuàng)建Model,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!ImmutableModel我們以UserModle為例,我們可以像這樣創(chuàng)建:public
class
UserModel:
NSObject
{
public
var
userId:
NSNumber
public
var
name:
String?
public
var
email:
String?
public
var
age:
Int?
public
var
address:
String?
init(userId:
NSNumber)
{
self.userId
=
userId
super.init()
}
}用的時候可以像這樣:let
userModel
=
UserModel(userId:
1)
user.email
=
"335050309@"
=
"roy"
user.age
=
27
user.address
=
"上海市楊浦區(qū)"這樣創(chuàng)建一個User對象好處是彈性很大,我可以隨意選擇設定某個property的值,但是背后同樣帶有很大的缺點,就是這個Model變得異常開放,不安分,這種Model我們一般叫MutableModel。有的時候我們需要MutableModel,但大部分的時候出于數(shù)據(jù)安全和解耦考慮我們不希望創(chuàng)建的property在外部可以隨意改變,在初始化后不可變的Model叫做ImmutableModel,在開發(fā)中我的建議盡量使用ImmutableModel。我們通過把property設置成readonly,在Swift可以用let或者private(set)。也就是這樣:public
class
UserModel:
NSObject
{
public
let
userId:
NSNumber
public
private(set)
var
name:
String?
public
private(set)
var
email:
String?
public
private(set)
var
age:
Int?
public
private(set)
var
address:
String?
}那么怎么寫初始化方法呢?Initializermappingargumentstoproperties當我們把property設置成readonly后,我們只能在init的時候賦值,這個時候就變成這樣:public
class
User:
NSObject
{
public
var
userId:
NSNumber
public
var
name:
String?
public
var
email:
String?
public
var
age:
Int?
public
var
address:
String?
init(userId:
NSNumber,
name:
String?,
email:
String,
age:
Int,
address:
String)
{
self.userId
=
userId
super.init()
=
name
self.email
=
self.age
=
age
self.address
=
address
}
}使用的時候就變成這樣:let
user
=
User.init(userId:
1,
name:
"335050309@",
email:
"roy",
age:
27,
address:
"上海市楊浦區(qū)")這樣創(chuàng)建Model安全可靠,大多數(shù)時候是有效的,但是也有一些缺點:如果property很多,init方法就有很多形參,然后變得又臭又長。有的時候我們只需要Model的某些property,這樣我們可能為各個不同的需求寫不同的init方法,最終讓UserModel變得很龐大。Initializertakingdictionary初始化的時候注入一個字典,就是下面的樣子:public
class
UserModel:
NSObject
{
public
let
userId:
NSNumber
public
private(set)
var
name:
String?
public
private(set)
var
email:
String?
public
private(set)
var
age:
Int?
public
private(set)
var
address:
String?
init(dic:
NSDictionary)
{
self.userId
=
(dic["userId"]
as?
NSNumber)!
super.init()
=
dic["name"]
as?
String
self.email
=
dic["email"]
as?
String
self.age
=
dic["age"]
as?
Int
self.address
=
dic["address"]
as?
String
}
}很顯然這解決上一種第一個缺點,但是還是有一個不足之處:如果字典沒有某個屬性對應的key的時候會崩潰,編譯器并不能幫助我們排查這種運行時的崩潰。不能很好的滿足某些時候只需要Model的某些property的需求。Mutablesubclass我們看看ImprovingImmutableObjectInitializationinObjective-C關于這個是怎么描述的Weendupunsatisfiedandcontinueourquestforthebestwaytoinitializeimmutableobjects.Cocoaisavastland,sowecan–andshould–stealsomeoftheideasusedbyAppleinitsframeworks.WecancreateamutablesubclassofReminderclasswhichredefinesallpropertiesasreadwrite:Weendupunsatisfiedandcontinueourquestforthebestwaytoinitializeimmutableobjects.Cocoaisavastland,sowecan–andshould–stealsomeoftheideasusedbyAppleinitsframeworks.WecancreateamutablesubclassofReminderclasswhichredefinesallpropertiesasreadwrite:@interface
MutableReminder
:
Reminder
<NSCopying,
NSMutableCopying>
@property
(nonatomic,
copy,
readwrite)
NSString
*title;
@property
(nonatomic,
strong,
readwrite)
NSDate
*date;
@property
(nonatomic,
assign,
readwrite)
BOOL
showsAlert;
@endAppleusesthisapproachforexampleinNSParagraphStyleandNSMutableParagraphStyle.Wemovebetweenmutableandimmutablecounterpartswith-copyand-mutableCopy.Themostcommoncasematchesourexample:abaseclassisimmutableanditssubclassismutable.AppleusesthisapproachforexampleinNSParagraphStyleandNSMutableParagraphStyle.Wemovebetweenmutableandimmutablecounterpartswith-copyand-mutableCopy.Themostcommoncasematchesourexample:abaseclassisimmutableanditssubclassismutable.Themaindisadvantageofthiswayisthatweendupwithtwiceasmanyclasses.What'smore,mutablesubclassesoftenexistonlyasawaytoinitializeandmodifytheirimmutableversions.Manybugscanbecausedbyusingamutablesubclassbyaccident.Forexample,amentalburdenshowsinsettingupproperties.Wehavetoalwayscheckifamutablesubclassexists,andifsousecopymodifierinsteadofstrongforthebaseclass.Themaindisadvantageofthiswayisthatweendupwithtwiceasmanyclasses.What'smore,mutablesubclassesoftenexistonlyasawaytoinitializeandmodifytheirimmutableversions.Manybugscanbecausedbyusingamutablesubclassbyaccident.Forexample,amentalburdenshowsinsettingupproperties.Wehavetoalwayscheckifamutablesubclassexists,andifsousecopymodifierinsteadofstrongforthebaseclass.大致意思是創(chuàng)建一個可變子類,它將所有屬性重新定義為readwrite。這種方式的主要缺點是我們最終得到兩倍的類。而且,可變子類通常僅作為初始化和修改其不可變版本的方式存在。偶然使用可變子類可能會導致許多錯誤。例如,在設置屬性時會出現(xiàn)心理負擔。我們必須始終檢查是否存在可變子類。還有一點這種方式只能在Objective-C中使用。BuilderpatternBuilderpattern模式需要我們使用一個Builder來創(chuàng)建目標對象,目標對象的property依舊是readonly,但是Builder的對應property卻可以選擇為readwrite。依舊用UserModel為例,我們需要為其進行適當?shù)母脑?,改造之后:typealias
UserModelBuilderBlock
=
(UserModelBuilder)
->
UserModelBuilder
public
class
UserModel:
NSObject{
public
let
userId:
NSNumber
public
private(set)
var
name:
String?
public
private(set)
var
email:
String?
public
private(set)
var
age:
Int?
public
private(set)
var
address:
String?
init(userId:
NSNumber)
{
self.userId
=
userId
super.init()
}
convenience
init(userId:
NSNumber
,with
block:
UserModelBuilderBlock){
let
userModelBuilder
=
block(UserModelBuilder.init(userId:
userId))
self.init(userId:
userModelBuilder.userId)
self.email
=
userModelBuilder.email
=
userModelB
self.age
=
userModelBuilder.age
self.address
=
userModelBuilder.address
}
}之后是對應的Builderclass
UserModelBuilder:
NSObject
{
public
let
userId:
NSNumber
public
var
name:
String?
public
var
email:
String?
public
var
age:
Int?
public
var
address:
String?
init(userId:
NSNumber)
{
self.userId
=
userId
super.init()
}
}然后可以像下面這樣使用:let
userModle
=
UserModel(userId:
1)
{
(builder)
->
UserModelBuilder
in
builder.email
=
"335050309@"
=
"roy"
builder.age
=
27
builder.address
=
"上海市楊浦區(qū)"
return
builder
}這種方式雖然我們需要為Model再創(chuàng)建一個Builder,略顯啰嗦和復雜,但是當property較多,對Model的需求又比較復雜的時候這又確實是一種值得推薦的方式。以上全是Swift的代碼實現(xiàn),下面我再貼上對應的OC代碼#import
<Foundation/Foundation.h>
@interface
RUserModelBuilder
:
NSObject
@property
(nonatomic,
strong,
readwrite,
nonnull)
NSNumber
*userId;
@property
(nonatomic,
copy,
readwrite,
nullable)
NSString
*name;
@property
(nonatomic,
copy,
readwrite,
nullable)
NSString
*email;
@property
(nonatomic,
copy,
readwrite,
nullable)
NSNumber
*age;
@property
(nonatomic,
copy,
readwrite,
nullable)
NSString
*address;
@end
typedef
RUserModelBuilder
*__nonnull(^RUserModelBuilderBlock)(RUserModelBuilder
*__nonnull
userModelBuilder);
@interface
RUserModel
:
NSObject
@property
(nonatomic,
strong,
readonly,
nonnull)
NSNumber
*userId;
@property
(nonatomic,
copy,
readonly,
nullable)
NSString
*name;
@property
(nonatomic,
copy,
readonly,
nullable)
NSString
*email;
@property
(nonatomic,
copy,
readonly,
nullable)
NSNumber
*age;
@property
(nonatomic,
copy,
readonly,
nullable)
NSString
*address;
+
(nonnull
instancetype)buildWithBlock:(nonnull
RUserModelBuilderBlock)builderBlock;
@end#import
"RUserModel.h"
@implementation
RUserModelBuilder
@end
@interface
RUserModel
()
@property
(nonatomic,
strong
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 建筑工程施工現(xiàn)場隱患排查治理制度
- 感恩父母演講稿 15篇
- 豬偽狂犬病凈化方案
- 施工組織設計方案編制審批制度
- 食堂營養(yǎng)方案
- 委托訂購機票合同
- “大閱讀”活動實施方案
- 煤炭加工煤炭脫硫除塵技術考核試卷
- “小學英語語篇有效教學策略研究”課題研究方案
- 金融科技趨勢與創(chuàng)新解析考核試卷
- 空調(diào)投標書(范本)
- 第四單元課文復習(課件)部編版語文五年級上冊
- 決議公開范文(推薦十九篇)
- 助產(chǎn)士的溝通技巧課件
- DB11-T 1913-2021 專業(yè)應急救援隊伍能力建設規(guī)范 燃氣
- 國際理解教育教案
- 健美操訓練計劃
- 深基坑安全管理(安全培訓)課件
- 領導力與團隊管理課件
- 樂山市市中區(qū)2022-2023學年上期期中測試七年級生物試題及答案
- 計算機組成與系統(tǒng)結構課后答案
評論
0/150
提交評論