Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializer element is not a compile time constant

Tags:

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
like image 245
user3681670 Avatar asked Dec 20 '25 01:12

user3681670


2 Answers

You should init the variable only inside a method

try override

 -(id) init
 {
  self = [super init];
  if(self)
  {
    myArray = [[NSMutableArray alloc] init];
  }
  return self;
 }
like image 150
Gal Marom Avatar answered Dec 22 '25 16:12

Gal Marom


Error

As the error say, you can only initialize compile time constant in the implementation of your class

This will work:

NSString* abcd = @"test";

Because @"test" is a constant and will never change after the compilation of your code.

[[NSMutableArray alloc] init] is not a constant and this is why you got an error. You will have to implement an init method to initialize your array.

Swift

For the swift part of your question:

You can still use NSArray in swift or use the swift Array type. You can check out the Working with Cocoa Data Types Documentation or the Apple collections types Swift Documentation.

If you still want to use NSArray in swift :

var array:NSMutableArray = NSMutableArray()
array.addObject("test1")
array.addObject("test2")
// or
array:NSMutableArray = ["test1", "test2"]

Or if you want to use the swift array :

var array:String[] = ["test1", "test2"]
// or
var array:String[] = String[]()
array.append("test1")
array.append("test2")
like image 43
olicarbo Avatar answered Dec 22 '25 17:12

olicarbo