android 中
自定義的對象序列化的問題有兩個(gè)選擇一個(gè)是Parcelable,另外一個(gè)是Serializable。一 序列化原因:
1.永久性保存對象,保存對象的字節(jié)序列到本地文件中;
2.通過序列化對象在網(wǎng)絡(luò)中傳遞對象;
3.通過序列化在進(jìn)程間傳遞對象。
二 至于選取哪種可參考下面的原則:
1.在使用內(nèi)存的時(shí)候,Parcelable 類比Serializable性能高,所以推薦使用Parcelable類。
2.Serializable在序列化的時(shí)候會產(chǎn)生大量的臨時(shí)變量,從而引起頻繁的GC。
3.Parcelable不能使用在要將數(shù)據(jù)存儲在磁盤上的情況,因?yàn)镻arcelable不能很好的保證數(shù)據(jù)的持續(xù)性在外界有變化的情況下。盡管Serializable效率低點(diǎn), 也不提倡用,但在這種情況下,還是建議你用Serializable 。
實(shí)現(xiàn):1 Serializable 的實(shí)現(xiàn),只需要繼承 implements Serializable 即可。這只是給對象打了一個(gè)標(biāo)記,系統(tǒng)會自動將其序列化。
2 Parcelabel 的實(shí)現(xiàn),需要在類中添加一個(gè)靜態(tài)成員變量 CREATOR,這個(gè)變量需要繼承 Parcelable.Creator 接口。
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
posted on 2011-09-16 16:16
lincode 閱讀(22137)
評論(0) 編輯 收藏 所屬分類:
android