iphone中Objective C中的静态字符串变量 [英] Static string variable in Objective C on iphone

查看:157
本文介绍了iphone中Objective C中的静态字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建&访问iPhone中的静态字符串(目标c)?
我在A类声明静态NSString * str = @OldValue

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

如果我指定B类中的一些值为 str = @NewValue
这个值对于B类中的所有方法都是持久的。但是如果我在C类中访问它(在B中赋值后),我将它作为OldValue获取。
我错过了什么吗?我应该在其他课程中使用extern吗?

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?

谢谢&此致,
Yogini

Thanks & Regards, Yogini

推荐答案

更新:从Xcode 8开始,Objective-C 具有类属性。注意,它主要是语法糖;这些属性不是自动合成的,因此实现与以前基本没有变化。

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"

参见 WWDC 2016 LLVM的新功能。类属性部分从大约5分钟开始。

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

原始答案:

Objective-C没有类变量,这是我认为你正在寻找的。你可以用静态变量伪装它,正如你所做的那样。

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.

我建议将静态NSString放在你的类的实现文件中,并提供类方法访问/改变它。这样的事情:

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

这篇关于iphone中Objective C中的静态字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆