如何检查 CGPoint 是否已初始化? [英] How do I check if a CGPoint has been initialised?
问题描述
我想最初将 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
,但这也是一个有效的坐标.或者你可以使用负的 x
和 y
值来标记一个未初始化"的点,因为负值不能是有效的绘图点,但这有点小技巧,
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:
- 将该属性存储为指向
CGPoint
的指针.未初始化时,此值可以设置为NULL
.当然,您必须担心malloc
ing 和free
ing 值. 将
CGPoint
与名为pointInitialized
或类似的BOOL
一起存储,最初设置为NO
,但是一旦点被初始化就设置为YES
.您甚至可以将其包装在一个结构中:
- Store the property as a pointer to a
CGPoint
. This value can be set toNULL
when uninitialized. Of course, you have to worry aboutmalloc
ing andfree
ing the value. Store the
CGPoint
alongside aBOOL
calledpointInitialized
or somesuch, initially set toNO
, but set toYES
once the point has been initialized. You can even wrap that up in a struct:
struct {
CGPoint point;
BOOL initialized;
} pointData;
这篇关于如何检查 CGPoint 是否已初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!