编码一个Objective-C块? [英] Encoding an Objective-c Block?

查看:82
本文介绍了编码一个Objective-C块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以用NSKeyedArchiver编码Objective-C块?

Is it possible to encode an Objective-C block with an NSKeyedArchiver?

我认为Block对象不是NSCoding兼容的,因此[coder encodeObject:block forKey:@"block"]不起作用?

I don't think a Block object is NSCoding-compliant, therefore [coder encodeObject:block forKey:@"block"] does not work?

有什么想法吗?

推荐答案

否,由于多种原因,这是不可能的.块中包含的数据的表示方式与实例变量类似.没有状态清单,因此也没有办法为存档目的枚举状态.

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

那么您可以:

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)

从那里,您可以在MyData上实现存档,将其保存,等等.关键是将Block视为进行计算的触发器,并将所述计算和计算的必要状态封装到MyData类的实例中

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.

这篇关于编码一个Objective-C块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆