目标C中的全局属性 [英] Global Property in Objective C

查看:95
本文介绍了目标C中的全局属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  typedef enum {
CalendarTypeMonth = 0,
CalendarTypeWeek
} CalendarType;

然后在我的视图控制器中,我确定日历类型应该是什么并将其存储在属性中:

  @property(非原子)CalendarType myCalendarType; 

现在我希望我项目中的所有类都可以访问日历类型。我怎样才能设置这个属性是全球/外部,使所有的类都可以读取?

编辑:我知道enum的定义将在项目中可用。但是我感兴趣的是 myCalendarType 值。如何访问所有类中myCalendarType的值?

解决方案

您可以声明类方法来访问静态变量。 >

将这些代码添加到您的实现文件中:

  static MyStaticType staticVar = MyStaticTypeDefault; 

+(BOOL)myStaticVar
{
return staticVar;
}

+(void)setMyStaticVar:(MyStaticType)newValue
{
staticVar = newValue;
}

然后在接口文件中为这些方法创建声明。
这比将所有静态值移动到AppDelegate好得多。
无论如何,很多变体都是可能的 - 例如,您可以创建singletone来存储应用程序的某些设置或使用CoreData。

I have an enum defined in the Constants.h file this way:

typedef enum {
    CalendarTypeMonth = 0,
    CalendarTypeWeek
} CalendarType;

Then in my view controller I determine what the calendar type should be and store it in a property this way:

@property (nonatomic) CalendarType myCalendarType;

Now I want all the classes in my project have access to the calendar type. How can I set this property to be global/extern so that all classes can read this?

EDIT: I know the definition of the enum will be available across the project. But what I am interested in is the value of myCalendarType. How can I access the value of myCalendarType across all classes?

解决方案

You can declare class method to access static variable.

Add such code to your implementation file:

static MyStaticType staticVar = MyStaticTypeDefault;

+(BOOL)myStaticVar
{
    return staticVar;
}

+(void)setMyStaticVar:(MyStaticType)newValue
{
    staticVar = newValue;
}

And create declarations for this methods in interface file. This is much better then moving all static values to AppDelegate. Anyway, a lot of variants are possible - for example, you can create singletone to store some settings of application or use CoreData.

这篇关于目标C中的全局属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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