用ARC编码和解码CGMutablePathRef

时间:2012-03-30 07:43:54

标签: ios memory-management automatic-ref-counting nscoding cgpath

在ARC下,是否可以使用CGMutablePathRefNSCoding(或其非可变形式)进行编码/解码?天真的我试着:

path = CGPathCreateMutable();
...
[aCoder encodeObject:path]

但是我从编译器得到一个友好的错误:

Automatic Reference Counting Issue: Implicit conversion of an Objective-C pointer to 'CGMutablePathRef' (aka 'struct CGPath *') is disallowed with ARC

我该怎么做才能对此进行编码?

3 个答案:

答案 0 :(得分:1)

NSCoding是一种协议。其方法只能用于符合NSCoding协议的对象。 CGPathRef甚至不是对象,因此NSCoding方法无法直接使用。这就是您收到错误的原因。

Here's a guy提出了一种序列化CGPath的方法。

答案 1 :(得分:1)

您的问题不是由于ARC,而是由于基于C的Core Graphics代码与基于Objective-C的NSCoding机制之间的不匹配。

要使用编码器/解码器,您需要使用符合Objective-C NSCoding协议的对象。 CGMutablePathRef不符合,因为它不是Objective-C对象而是Core Graphics对象引用。

但是,UIBezierPath是CGPath的Objective-C包装器,它确实符合。

您可以执行以下操作:

CGMutablePathRef mutablePath = CGPathCreateMutable();
// ... you own mutablePath. mutate it here...
CGPathRef persistentPath = CGPathCreateCopy(mutablePath);
UIBezierPath * bezierPath = [UIBezierPath bezierPathWithCGPath:persistentPath];
CGPathRelease(persistentPath);
[aCoder encodeObject:bezierPath];

然后解码:

UIBezierPath * bezierPath = [aCoder decodeObject];
if (!bezierPath) { 
  // workaround an issue, where empty paths decode as nil
  bezierPath = [UIBezierPath bezierPath]; 
}
CGPathRef  path = [bezierPath CGPath];
CGMutablePathRef * mutablePath = CGPathCreateMutableCopy(path);
// ... you own mutablePath. mutate it here 

这适用于我的测试。

答案 2 :(得分:0)

如果要求持久存储CGPath,则应使用CGPathApply函数。检查here了解如何执行此操作。