encoderWithCoder:
方法不會被調用,因爲XCode將對象圖編碼到xib中的時間不是運行時間,它不能調用您的encoderWithCoder:
方法。
How does Interface Builder serialize the object graph?
如果打開廈門國際銀行作爲源代碼,你可以看到它是這樣的:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="4514" systemVersion="13B42" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none">
<dependencies>
<deployment defaultVersion="1536" identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="3747"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="EMXibViewController">
<connections>
<outlet property="view" destination="1" id="3"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="1">
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<view contentMode="scaleToFill" id="XyJ-CF-vRx">
<rect key="frame" x="68" y="102" width="204" height="403"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="0.0" alpha="1" colorSpace="calibratedWhite"/>
</view>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<simulatedStatusBarMetrics key="simulatedStatusBarMetrics"/>
<simulatedScreenMetrics key="simulatedDestinationMetrics" type="retina4"/>
</view>
</objects>
</document>
我們可以看到,廈門國際銀行只保留對象的非默認值之間的關係他們。
的廈門國際銀行的UIViewController中,有隻有兩個UI對象,一個是UIViewController的觀點,另一個是它的子視圖讓我們說這mysubview
和有關會談如何XCode的存檔mysubview
。
我已經改變其的backgroundColor,幀和mysubview
autoresizingMask屬性,採取backgroundColor
屬性作爲例子,backgroundColor屬性被保存爲「彩色鍵=」的backgroundColor「白色=‘0.0’阿爾法=‘1’色彩空間=」 calibratedWhite 「」。它將歸檔mysubview
的backgroundColor。
Xib只是歸檔了mysubview
對象的backgroundColor和autoresizingMask和frame屬性,當加載xib時,它會調用UIView的initWithCoder
方法。在該方法中,它將獲得用於關鍵字@「backgroundColor」的UIColor對象和用於關鍵字@「frame」的CGRect以及用於關鍵字「@ autoresizingMask」的UIViewAutoresizing,而UIView的任何其他屬性都被分配了默認值。
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder] ;
UIColor * backgroundColor = [aDecoder decodeIntegerForKey:@"backgroundColor"] ;
if (backgroundColor) {
self.backgroundColor = backgroundColor ;
} else {
self.backgroundColor = $(defaultColor) ; // if no key in xib, use the default value.
}
// more...
return self ;
}
這是一個不錯的問題,讓我多想一想。
請注意,您可以在IB中添加「用戶定義的運行屬性」(選擇視圖並轉至檢查器的第三個選項卡)。當它被取消存檔IIRC(使用你的屬性的setter方法)時,這些將被設置在你的對象上。 – Taum