Converting a CGPoint to NSValue

2019-01-25 04:19发布

In CABasicAnimation.fromValue I want to convert a CGPoint to a "class" so I used NSValue valueWithPoint but in device mode or simulator one is not working... need to use NSMakePoint or CGPointMake if in device or simulator.

6条回答
Juvenile、少年°
2楼-- · 2019-01-25 04:28

&(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

查看更多
Root(大扎)
3楼-- · 2019-01-25 04:30

@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

查看更多
霸刀☆藐视天下
4楼-- · 2019-01-25 04:33

In Swift, you can change a value like this:

    var pointValueare = CGPointMake(30,30)
    NSValue(CGPoint: pointValueare)
查看更多
贪生不怕死
5楼-- · 2019-01-25 04:47

There is a UIKit addition to NSValue that defines a function

+ (NSValue *)valueWithCGPoint:(CGPoint)point

See iPhone doc

查看更多
smile是对你的礼貌
6楼-- · 2019-01-25 04:50

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

var pointValue = CGPointMake(10,10)
NSValue(CGPoint: pointValue)
查看更多
我命由我不由天
7楼-- · 2019-01-25 04:51

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));
}
查看更多
登录 后发表回答