I want to store my CGPoint to the NSMutable Array, so , I have method like this:
[self.points addObject:CGPointMake(x, y)];
But I got the error, it said that :
Incompatible type for argument 1 of "addObject".
So, I check out the API,
- (void)addObject:(id)anObject
anObject The object to add to the end of the receiver's content. This value must not be nil.
So, I think the "CGPointMake" can make a Object, but it can't be assigned. What happens?
To build on the answer given by atbreuer11, you can convert your CGPoint to NSValue, store it in NSMutableArray and convert it back using the following:
Then restore it again:
That's probably the easiest way to do it. You can write a complete class and do all types of data manipulation, but I think it would be an overkill, unless you really have to.
Unfortunately for you a CGPoint isn't an Objective-c object. It is a c struct. if you Apple double click on CGPoint you should jump to the definition
If you want to store CGPoint in an NSArray you will need to wrap them first. You can use NSValue for this or write your own wrapper.
see Converting a CGPoint to NSValue
EDIT> There is a small overhead for each objective-c method call, and creating and destroying objects involves many method calls before they are even used for anything. You shouldn't worry about this normally but for very small objects which encapsulate little behaviour and that have short lifetimes it can affect performance. If Apple used objects for all points, rect, sizes and even ints, floats, etc performance would be worse.
The problem is that CGPoint is actually just a C structure it is not an object:
If you are on the iPhone you can use the NSValue UIKit additions to convert the CGPoint to an NSValue object.
See this previous answer for examples: How can I add CGPoint objects to an NSArray the easy way?
A simple way to handle
CGPoint
(or any other nonNSObject
inherited structure) is to create a new class inherited fromNSObject
.The code is longer, but clean. An example is below:
In .h file:
In .m file:
Here is some code sample showing the usage, do not forget to release!!!
You can also do the following:
Swift 3.x
// Convert CGPoint to NSValue
// Restore it again