user3009729
user3009729

Reputation: 75

Global variables not initializing

I have found several explanations how to fix this but none of them (that I found) are simple enough for me to understand. New to Objective-c.

I am looking to access an array in multiple classes in objective c. I am trying to create a global variable (I know inefficient) in a "Globals.h" class, Initialize them in another class, and access that information in yet another class.

Heres what I have.

In Globals.h

#import <UIKit/UIKit.h>

extern NSArray *globalRows;

@interface Globals : NSObject

@end

ViewController.m

#import "Globals.h"

-(void)initGlobal{
    globalRows = [[NSArray alloc] initWithArray:rows];
}

The compiler does not want to Initialize the variable and I do not understand why.

EDIT:
The Globals class is only to hold the global variables there is no executable code in this class.

The reason I initialize in the ViewController is that is where the information needed is parsed and stored.

There is no error and the code will simply not compile.

EDIT2:

It seems I have found a very good explanation here!

Upvotes: 0

Views: 67

Answers (1)

0xFADE
0xFADE

Reputation: 832

NSObjects have a + (void)initialize method you can setup that get called during startup. You could also just call it from main as well.

Still, a better design pattern is to make a singleton to hold some global thing you want to access/use. Similarly putting the things inside your app delegate make them effectively global.

Upvotes: 1

Related Questions