【问题标题】:Having trouble retaining a CGPath object (warning appears)无法保留 CGPath 对象(出现警告)
【发布时间】:2012-07-27 21:50:25
【问题描述】:

我有一个实例变量 CGMutablePathRef _mutablePath ,我将其设置为 @property (nonatomic) CGMutablePathRef mutablePath; 。我重写了setter方法:

- (void) setMutablePath:(CGMutablePathRef)mutablePath
{
    if (_mutablePath)
    {
        CGPathRelease(_mutablePath);
        _mutablePath = NULL;
    }

    _mutablePath = CGPathRetain(mutablePath);
}

但是我在这一行收到警告:_mutablePath = CGPathRetain(mutablePath);,上面写着:

Assigning to 'CGMutablePathRef' (aka 'struct CGPath *') from 'CGPathRef' (aka 'const struct CGPath *') discards qualifiers

为什么这不起作用?当我这样做时,这似乎适用于 CT(核心文本)对象。我尝试了许多不同的演员阵容,但无法让错误消失,任何建议都将不胜感激。

【问题讨论】:

  • 虽然与问题没有直接关系,但您应该防止出现mutablePath == _mutablePath 因为您在保留之前释放。
  • 感谢会这样做。所以最终这是为了防止在可变路径已经等于_mutablepath的情况下浪费时间?或者是否会出现其他副作用(如果有,我看不到)。
  • 不,不仅仅是为了性能。当您调用 release 时,如果您的对象是唯一持有对路径的引用的对象,它将被释放。因此,当您调用保留时,它将无效/解除分配。您可以通过在发布之前调用 retain 或显式检查是否相等来解决此问题。
  • 我看到它是双向的,我想这是个人品味的问题。这是发布前的保留。 CGMutablePathRef tmp = (CGMutablePathRef)CGPathRetain(mutablePath); if(_mutablePath) { CGPathRelease(_mutablePath); _mutablePath = NULL; } _mutablePath = tmp;
  • @idz:tmp 是不必要的,因为CGPathRetain() 必须返回其输入参数。你可以直接说CGPathRetain(mutablePath); CGPathRelease(_mutablePath); _mutablePath = mutablePath;,完全没有条件。

标签: iphone ios cocoa-touch core-graphics


【解决方案1】:

CGPathRetain() 被声明为

CGPathRef CGPathRetain(CGPathRef path);

这意味着它返回 CGPathRef 而不是 CGMutablePathRef。在将结果分配给 _mutablePath ivar 之前,您应该将结果转换回 CGMutablePathRef

【讨论】:

  • 谢谢。我一直在 CGPathRetain 调用内部而不是外部进行转换,这是我的愚蠢错误。
猜你喜欢
  • 2019-05-14
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
  • 2011-07-11
  • 1970-01-01
相关资源
最近更新 更多