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.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
CiNN
  • 9,752
  • 6
  • 44
  • 57

7 Answers7

53

There is a UIKit addition to NSValue that defines a function

+ (NSValue *)valueWithCGPoint:(CGPoint)point

See iPhone doc

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
ashcatch
  • 2,327
  • 1
  • 18
  • 29
13

@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

Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
DanSkeel
  • 3,853
  • 35
  • 54
  • 3
    But 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
3

In Swift, you can change a value like this:

    var pointValueare = CGPointMake(30,30)
    NSValue(CGPoint: pointValueare)
Sk Rejabul
  • 33
  • 1
  • 8
1

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

var pointValue = CGPointMake(10,10)
NSValue(CGPoint: pointValue)
Antoine
  • 23,526
  • 11
  • 88
  • 94
1

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

user738872
  • 11
  • 1
0

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

Guillaume Algis
  • 10,705
  • 6
  • 44
  • 72
-2

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));
}
Marc Charbonneau
  • 40,399
  • 3
  • 75
  • 82