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.
7 Answers
There is a UIKit
addition to NSValue
that defines a function
+ (NSValue *)valueWithCGPoint:(CGPoint)point
See iPhone doc

- 23,586
- 12
- 103
- 136

- 2,327
- 1
- 18
- 29
-
Thanks, very helpful, but consider that these methods copy values. Checkout my answer. – DanSkeel Jun 19 '12 at 17:55
@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

- 23,586
- 12
- 103
- 136

- 3,853
- 35
- 54
-
3But be careful with the second approach since in the example, you store a pointer to a memory location on the heap. So if you use the created NSValue object (or rather the pointer stored in it) after you left the scope of the point declaration, your application might crash. – ashcatch Jun 03 '14 at 07:15
In Swift, you can change a value like this:
var pointValueare = CGPointMake(30,30)
NSValue(CGPoint: pointValueare)

- 33
- 1
- 8
In Swift the static method is change to an initialiser method:
var pointValue = CGPointMake(10,10)
NSValue(CGPoint: pointValue)

- 23,526
- 11
- 88
- 94
&(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

- 11
- 1
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.

- 10,705
- 6
- 44
- 72
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));
}

- 40,399
- 3
- 75
- 82
-
1
-
that syntax is **wrong**, so the function, whatever it is… (it's not explained), is _useless_. – Alex Gray Dec 01 '11 at 16:50
-
The syntax is correct, but the cast is useless, *CGPoint* and *NSPoint* are the same type (*NSPoint* it typedef'd to be a *CGPoint*). – Ramy Al Zuhouri Jun 18 '13 at 15:39