简体   繁体   English

编码Objective-c块?

[英]Encoding an Objective-c Block?

Is it possible to encode an Objective-C block with an NSKeyedArchiver ? 是否可以使用NSKeyedArchiver编码Objective-C块?

I don't think a Block object is NSCoding -compliant, therefore [coder encodeObject:block forKey:@"block"] does not work? 我认为Block对象不符合NSCoding ,因此[coder encodeObject:block forKey:@"block"]不起作用?

Any ideas? 有任何想法吗?

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. 从那里,您可以在MyData上实现归档,将其保存,等等......关键是将Block视为执行计算的触发器,并将所述计算和计算的必要状态封装到MyData类的实例中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM