Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Best way to have a global string - as for a notification name

I keep reading different things about this and it seems dangerously confusing. Can someone please tell me the proper pattern to define notification strings that can be used globally? Everything I've tried have caused linker errors. For example, in my GlobalVariables singleton I added:

#import <Foundation/Foundation.h>
extern NSString *kMPTimeChanged;

@interface GlobalVariables : NSObject etc. 

And then in the init:

@implementation GlobalVariables

#pragma mark Singleton Methods

+ (id)sharedGlobals {
    static GlobalVariables *sharedGlobals = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedGlobals = [[self alloc] init];

    });
    return sharedGlobals;
}

- (id)init {
    if (self = [super init]) {

      kMPTimeChanged=@"kMPTimeChanged";

    return self;
}

It didn't build, I got multiple errors.

like image 504
JoshDG Avatar asked Nov 29 '22 12:11

JoshDG


2 Answers

In your .h file you should write:

extern NSString * const kMPTimeChanged;

In your .m file, you should write:

NSString * const kMPTimeChanged = @"My Constant";

Both of these of these should be outside of your @interface and @implementation blocks.

like image 170
Holly Avatar answered Dec 05 '22 14:12

Holly


I'd recommend declaring your variables as const extern. Then:

// Globals.h
extern NSString * const kMPTimeChanged;

// Globals.m
NSString * const kMPTimeChanged = @"...";
like image 31
Kevin Sylvestre Avatar answered Dec 05 '22 13:12

Kevin Sylvestre