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

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

问题描述

如何创建 &访问 iPhone 中的静态字符串(目标 c)?我在 A 类中声明了 static 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?

谢谢&问候,瑜珈

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天全站免登陆