Static string variable in Objective C on iphone

前端 未结 2 1872
臣服心动
臣服心动 2020-12-01 01:08

How to create & access static string in iPhone (objective c)? I declare static NSString *str = @\"OldValue\" in class A.

If i assign some value to

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 01:30

    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
    

提交回复
热议问题