Objective-c – Initializer element is not a compile time constant

objective c

Using objective-c to write a program. I'm getting an error (initializer element is not a compile-time constant) and am not sure I follow why it's occurring. I'm just trying to initialize an array. I'm also using xcode6. My questions are: how can I rewrite this correctly in Objective-c and what would it look like in the new Swift? Also why is there an error – I don't follow how to implement some of the other threads on this question?

Name.h

#import <Foundation/Foundation.h>

@interface Name : NSObject
@property (nonatomic, retain) NSMutableArray *myArray;

@end

Name.m

#import "Name.h"

@implementation Name

NSMutableArray *myArray = [[NSMutableArray alloc] init]; //error shows up here - initializer element is not a compile-time constant

[myArray addObject:@"Object 1"];

[myArray addObject:@"Object 2"];

[myArray addObject:@"Object 3"];

@end

Best Answer

You should init the variable only inside a method

try override

 -(id) init
 {
  self = [super init];
  if(self)
  {
    myArray = [[NSMutableArray alloc] init];
  }
  return self;
 }