Static string variable in Objective C on iphone

Update: As of Xcode 8, Objective-C does have class properties. Note, it’s mostly syntactic sugar; these properties are not auto-synthesized, so the implementation is basically unchanged from before.

// MyClass.h
@interface MyClass : NSObject
@property( class, copy ) NSString* str;
@end

// MyClass.m
#import "MyClass.h"

@implementation MyClass

static NSString* str;

+ (NSString*) str 
{
    return str;
}

+ (void) setStr:(NSString*)newStr 
{
    if( str != newStr ) {
        str = [newStr copy];
    }
}
@end


// Client code
MyClass.str = @"Some String";
NSLog( @"%@", MyClass.str ); // "Some String"

See WWDC 2016 What’s New in LLVM. The class property part starts at around the 5 minute mark.

Original Answer:

Objective-C doesn’t have class variables, which is what I think you’re looking for. You can kinda fake it with static variables, as you’re doing.

I would recommend putting the static NSString in the implementation file of your class, and provide class methods to access/mutate it. Something like this:

// MyClass.h
@interface MyClass : NSObject {
}
+ (NSString*)str;
+ (void)setStr:(NSString*)newStr;
@end

// MyClass.m
#import "MyClass.h"

static NSString* str;

@implementation MyClass

+ (NSString*)str {
    return str;
}

+ (void)setStr:(NSString*)newStr {
    if (str != newStr) {
        [str release];
        str = [newStr copy];
    }
}
@end

Leave a Comment