decodeTopLevelObjectOfClass用于unarchieving的目的是什么

时间:2018-03-09 10:08:35

标签: ios objective-c

为什么我们应该使用decodeTopLevelObjectOfClass而不是decodeObjectOfClass?在我的情况下,如果嵌套的自定义对象有效,则decodeObjectOfClass不起作用。

1 个答案:

答案 0 :(得分:0)

-[NSCoder error]有关。

NSCoder.h中的标题-failWithError:中注释:

Sets an error on this NSCoder once per TopLevel decode; calling it
repeatedly will have no effect until the call stack unwinds to one
of the TopLevel decode entry-points.

This method is only meaningful to call for decodes.

Typically, you would want to call this method in your -initWithCoder:
implementation when you detect situations like:
 - lack of secure coding
 - corruption of your data
 - domain validation failures

After calling -failWithError: within your -initWithCoder:
implementation, you should clean up and return nil as early as possible.

Once an error has been signaled to a decoder, it remains set until
it has handed off to the first TopLevel decode invocation above it.
For example, consider the following call graph:
 A    -decodeTopLevelObjectForKey:error:
 B        -initWithCoder:
 C            -decodeObjectForKey:
 D                -initWithCoder:
 E                    -decodeObjectForKey:
 F                        -failWithError:

In this case the error provided in stack-frame F will be returned
via the outError in stack-frame A. Furthermore the result object
from decodeTopLevelObjectForKey:error: will be nil, regardless of
the result of stack-frame B.

NSCoder implementations support two mechanisms for the stack-unwinding from F to A:
 - forced (NSException based)
 - particpatory (error based)

The kind of unwinding you get is determined by the decodingFailurePolicy
property of this NSCoder (which defaults to NSDecodingFailurePolicyRaiseException
to match historical behavior).

对于-error

While .error is non-nil, all attempts to decode data from this
coder will return a nil/zero-equivalent value.

This error is consumed by a TopLevel decode API (which resets
this coder back to a being able to potentially decode data).