Encoding an Objective-c Block?

会有一股神秘感。 提交于 2019-11-30 08:17:18
bbum

No, it isn't possible for a variety of reasons. The data contained within a block isn't represented in any way similar to, say, instance variables. There is no inventory of state and, thus, no way to enumerate the state for archival purposes.

Instead, I would suggest you create a simple class to hold your data, instances of which carry the state used by the blocks during processing and which can be easily archived.

You might find the answer to this question interesting. It is related.


To expand, say you had a class like:

@interface MyData:NSObject
{
    ... ivars representing work to be done in block
}

- (void) doYourMagicMan;
@end

Then you could:

MyData *myWorkUnit = [MyData new];

... set up myWorkUnit here ...

[something doSomethingWithBlockCallback: ^{ [myWorkUnit doYourMagicMan]; }];

[myWorkUnit release]; // the block will retain it (callback *must* Block_copy() the block)

From there, you could implement archiving on MyData, save it away, etc... The key is treat the Block as the trigger for doing the computation and encapsulate said computation and the computation's necessary state into the instance of the MyData class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!