1

For example I want to store this in an ivar:

CGFloat color[4] = {red, green, blue, 1.0f};

so would I put this in my header?

CGFloat color[];

How would I assign values to that guy later? I mean I can't change it, right?

3 Answers 3

2

Instance variables are zeroed out on allocation so you can't use initialisers with them.

You need something like this:

// MyObject.h

@interface MyObject
{
    CGFloat color[4];
}
@end

// MyObject.m

@implementation MyObject

-(id) init
{
    self = [super init];
    if (self != nil)
    {
        color[0] = red;
        color[1] = green;
        color[2] = blue;
        color[3] = alpha;
    }
    return self;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I did pretty much this for an array stuffed with CGPoints, it works fine. I'm guessing that since the array is declared on the heap during the initialization of the object, that when the object goes away - so does the array? At least I'm hoping, or do you under ARC, have to make your own -(void)dealloc method and free() the array there?
0

You'd need to put the size in so that enough space is reserved.

CGFloat color[4];

Or use a pointer to the array, but that's more work and hardly superior for representing something as well-known as a color.

1 Comment

that doesn't seem to work. I had tried that with compiler errors.
0

You are better off using a NSColor object if you can.

However, to your original question one of my first questions is where do you want to create this array. When you say put it in a header do you mean as a member of a class or as a global array, you certainly can do both however there are some serious gotchas with putting globals in headers. If you need that follow up and I can explain it better.

If it is in a class then you can just declare it like any other member field. If you say

CGFloat color[4];

then the space for the array is allocated in your object itself. You can also just use a

CGFloat *color;

or its moral equivalent to refer to an array that is stored outside of the object. You do need to manage that storage appropriately however.

This matters in the case you hinted at where you use a constant array object and cannot later change it. That can happen but is rare, since it cannot happen with the first approach, you don't see it in the wild very often.

There is a whole dissertation on the corner cases in here, I am sure it is not helping to go into it. Just use CGFloat color[4] in your object and it won't matter, by the time you see things they will be mutable and you can just use them the way you expect.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.