encoderWithCoder:方法不会被调用,因为XCode将对象图编码成xib的时间不是运行时间,它不能调用你的encoderWithCoder:方法。
How does Interface Builder serialize the object graph?
如果你打开Xib作为源代码,你可以看到它是这样的:
<?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>
我们可以看到xib只保留了object的non-default值以及它们之间的关系。
xib 一个 UIViewController 并且只有两个 UI 对象,一个是 UIViewController 的视图,另一个是子视图让我们说它mysubview 并谈论 XCode 如何归档 mysubview。
我修改了mysubview的backgroundColor、frame和autoresizingMask属性,以backgroundColor属性为例,backgroundColor属性保存为"color key="backgroundColor" white="0.0" alpha="1" colorSpace ="校准白""。它将归档mysubview的背景颜色。
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 ;
}
这是一个很好的问题,让我思考更多。