Structs
suggest changeSyntax
- typedef struct { typeA propertyA; typeB propertyB; … } StructName
Remarks
In Objective-C, prefer an object unless a struct is a better fit. Cases where a struct is better:
- When you’re going to be creating and destroying a lot of values of the (struct) type, so you need good performance and small memory usage
- Structs are faster to create and use because when calling a method on an object, the method has to be determined at runtime
- Structs are smaller because a normal object also stores an
isapointer to its class - When the value has only a couple of fields and a small total size (
CGSizeis twoCGFloats: 4 bytes each on 32-bit, 8 bytes each on 64-bit), and it is used a lot (ties in with the first point) - When you could use unions or bitfields, and importantly, need the size saved by them because you need small memory usage (ties in with the first point)
- When you really want to store an array inside of the struct, since Objective-C objects can’t directly store C-arrays. However, note that you can still “indirectly” get an array in an Objective-C object by making it a reference (i.e.
type *in place of the C-arraytype[]) - When you need to communicate with some other code, such as a library, that’s coded in C; structs are fully implemented in C but objects are not
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents