Converting a CGPoint to NSValue

早过忘川 提交于 2019-11-29 05:34:34
ashcatch

There is a UIKit addition to NSValue that defines a function

+ (NSValue *)valueWithCGPoint:(CGPoint)point

See iPhone doc

DanSkeel

@ashcatch 's answer is very helpful, but consider that those methods from addition copy values, when native NSValue methods store pointers! Here is my code checking it:

CGPoint point = CGPointMake(2, 4);
NSValue *val = [NSValue valueWithCGPoint:point];
point.x = 10;
CGPoint newPoint = [val CGPointValue];

here newPoint.x = 2; point.x = 10


CGPoint point = CGPointMake(2, 4);
NSValue *val = [NSValue valueWithPointer:&point];
point.x = 10;
CGPoint *newPoint = [val pointerValue];

here newPoint.x = 10; point.x = 10

In Swift, you can change a value like this:

    var pointValueare = CGPointMake(30,30)
    NSValue(CGPoint: pointValueare)

&(cgpoint) -> get a reference (address) to cgpoint (NSPoint *)&(cgpoint) -> casts that reference to an NSPoint pointer *(NSPoint )(cgpoint) -> dereferences that NSPoint pointer to return an NSPoint to make the return type happy

In Swift the static method is change to an initialiser method:

var pointValue = CGPointMake(10,10)
NSValue(CGPoint: pointValue)

If you are using a recent-ish version of Xcode (post 2015), you can adopt the modern Objective-C syntax for this. You just need to wrap your CGPoint in @():

CGPoint primitivePoint = CGPointMake(4, 6);
NSValue *wrappedPoint = @(primitivePoint);

Under the hood the compiler will call +[NSValue valueWithCGPoint:] for you.

https://developer.apple.com/library/archive/releasenotes/ObjectiveC/ModernizationObjC/AdoptingModernObjective-C/AdoptingModernObjective-C.html

Don't think of it as "converting" your point-- NSValue is a wrapper class that holds primitive structs like NSPoint. Anyway, here's the function you need. It's part of Cocoa, but not Cocoa Touch. You can add the entire function to your project, or just do the same conversion wherever you need it.

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