How can I add CGPoint objects to an NSArray the easy way?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
CGPoint is a C struct, while NSArray stores Objective-C objects. Because of that mismatch, points must be boxed before insertion into Objective-C collections. The standard approach is using NSValue, which safely wraps and unwraps Core Graphics structs.
This pattern is stable, readable, and compatible with both legacy Objective-C APIs and mixed Swift projects.
Store CGPoint Values with NSValue
Use valueWithCGPoint: when adding points to mutable arrays.
This is the cleanest method for Objective-C APIs that need array storage.
Read Points Back Correctly
Unbox with CGPointValue before geometry operations.
Avoid pointer casts or manual memory tricks. NSValue handles layout correctly.
Use Typed Collections for Clarity
Modern Objective-C supports lightweight generics for readability:
This helps static analysis and makes intent clear during reviews.
Bridge with Swift Cleanly
Swift arrays can store CGPoint directly. When crossing Objective-C boundaries, convert explicitly.
Keep boxing at boundaries so internal Swift logic can use value types directly.
Reusable Helper Functions
If your code frequently boxes points, helper functions reduce noise.
Central helpers also reduce copy-paste bugs across rendering modules.
Performance Considerations
Boxing and unboxing has overhead. For performance-sensitive loops such as hit testing thousands of points per frame, prefer native buffers or Swift [CGPoint] internally, then box only when required by Objective-C APIs.
Good pattern:
- compute with native point arrays,
- convert to an
NSValuearray only at API boundary.
This balances speed and interoperability.
Validate Round-Trip Accuracy
Add quick tests for precision and order preservation.
Include negative and fractional coordinates in tests, especially for drawing and layout code.
Convenience Category for Cleaner Call Sites
If your project stores many geometric structs, a small category around NSValue improves readability and avoids accessor mistakes.
Using project-specific names can make code search easier and enforce consistent boxing conventions across modules.
Common Pitfalls
- Trying to insert raw
CGPointstructs directly intoNSArray. - Using the wrong unboxing accessor for stored struct types.
- Performing geometry math on boxed values without unboxing first.
- Overusing boxed point arrays in tight rendering loops.
- Mixing coordinate spaces without documenting expected input and output.
Summary
- '
CGPointmust be boxed asNSValuefor Objective-C array storage.' - Use
valueWithCGPoint:andCGPointValuefor safe conversion. - Keep boxing at API boundaries when working with Swift value arrays.
- Add helpers and tests for clarity and reliability.
- Prefer native point containers in performance-critical paths.

