Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

Static string variable in Objective C on iphone

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 this in class B as str = @"NewValue". This value persists for all methods in class B. But if I access it in class C (after assignment in B) I am getting it as OldValue. Am I missing something? Should i use extern in other classes?

Thanks & Regards, Yogini

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...