如何检查 CGPoint 是否已初始化? [英] How do I check if a CGPoint has been initialised?

查看:68
本文介绍了如何检查 CGPoint 是否已初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想最初将 CGPoint 属性设置为特定点(屏幕中间).其他方法随后可能希望更改此属性.我的想法是如果 getter 中为空就初始化它,但是我得到消息无效参数类型 'struct CGPoint' 到一元表达式.我也试过使用 if property == nil 或 0 但没有乐趣.

I would like to initially set a CGPoint property to a particular point (middle of screen). Other methods may subsequently wish to change this property. My thoughts were to initialise it if empty in the getter, but I get the message invalid argument type 'struct CGPoint' to unary expression. I also tried using if property == nil or 0 but no joy.

有什么想法吗?

-(CGPoint)graphOrigin
{
    // initialise to centre of screen if has not been set
    if(!_graphOrigin) // this expression is causing the problem
    {
        CGPoint origin = CGPointMake(self.bounds.origin.x + self.bounds.size.width / 2, self.bounds.origin.y + self.bounds.size.height / 2);

        _graphOrigin = origin;
    }

return _graphOrigin;

}

推荐答案

CGPoint 是一个结构体,因此您不能将其设置为 nil 或 NULL(它不是指针).从某种意义上说,真的没有未初始化"状态.也许您可以使用 {0.0, 0.0} 来指定一个未设置的 CGPoint,但这也是一个有效的坐标.或者你可以使用负的 xy 值来标记一个未初始化"的点,因为负值不能是有效的绘图点,但这有点小技巧,

A CGPoint is a struct, so you can't set it to nil or NULL (it's not a pointer). In a sense, there's really no "uninitialized" state. Perhaps you could use {0.0, 0.0} to designate an unset CGPoint, but that's also a valid coordinate. Or you could use negative x and y values to flag an "uninitialized" point, since negative values can't be valid drawing points, but that's a bit of a hack, too.

可能你最好的办法是做两件事之一:

Probably your best bet is to do one of two things:

  1. 将该属性存储为指向 CGPoint 的指针.未初始化时,此值可以设置为 NULL.当然,您必须担心mallocing 和freeing 值.
  2. CGPoint 与名为 pointInitialized 或类似的 BOOL 一起存储,最初设置为 NO,但是一旦点被初始化就设置为 YES.您甚至可以将其包装在一个结构中:

  1. Store the property as a pointer to a CGPoint. This value can be set to NULL when uninitialized. Of course, you have to worry about mallocing and freeing the value.
  2. Store the CGPoint alongside a BOOL called pointInitialized or somesuch, initially set to NO, but set to YES once the point has been initialized. You can even wrap that up in a struct:

struct {
    CGPoint point;
    BOOL initialized;
} pointData;

这篇关于如何检查 CGPoint 是否已初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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