Encode and Decode CGMutablePathRef with ARC

淺唱寂寞╮ 提交于 2019-12-08 09:46:08

问题


Under ARC, is it possible to encode/decode a CGMutablePathRef (or its non-mutable form) using NSCoding? Naively I try:

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

but I get a friendly error from the compiler:

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

What can I do to encode this?


回答1:


NSCoding is a protocol. Its methods can only be used with objects that conform to the NSCoding protocol. a CGPathRef isn't even an object, so NSCoding methods won't work directly. That's why you're getting that error.

Here's a guy who has come up with a way to serialize CGPaths.




回答2:


Your problem is not due to ARC, but to the mismatch between Core Graphics code based in C and the NSCoding mechanism based in Objective-C.

To use encoders/decoders, you need to use objects that conform to the Objective-C NSCoding protocol. CGMutablePathRef does not conform since it is not an Objective-C object but a Core Graphics object reference.

However, UIBezierPath is an Objective-C wrapper for a CGPath and it does conform.

You can do the following:

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

and then to decode:

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 

This works in my tests.




回答3:


If you asking for storing CGPath persistently you should you use the CGPathApply function. Check here for how to do that.



来源:https://stackoverflow.com/questions/9938864/encode-and-decode-cgmutablepathref-with-arc

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