【问题标题】:Global variables and objects in Objective C. What is the best way?Objective C中的全局变量和对象。最好的方法是什么?
【发布时间】:2014-02-17 16:22:51
【问题描述】:

我想为 iphone 项目使用全局变量和对象。

我创建了 NSobject 类并定义如下:

.h 文件:

#import <Foundation/Foundation.h>

@interface GlobelClass : NSObject

extern NSString *mystr;

extern NSMutableArray *Arrdata;

@end

.m 文件:

#import "GlobelClass.h"

@implementation GlobelClass

NSString *mystr;
NSMutableArray *Arrdata;
@end

什么是最好的方法或者我应该使用如下链接答案的单例模式: Using global variables in Objective-C

请分享想法?

【问题讨论】:

  • 这些是常数吗?它们是用来做什么的?为什么是全球性的?

标签: iphone object singleton global-variables extern


【解决方案1】:

在应用程序中使用全局变量的一种方式是:

您可以使用 App Delegate 类本身:

.h 文件:

AppDelegate: UIResponder <UIApplicationDelegate> {

}

@property(nonatomic,strong) NSString* strUserID;

.m 文件:

@synthesize strUserID;

现在您可以在 UIViewController 中将 strUserID 作为全局变量访问:

ABCProjectAppDelegate *appDelegate = (ABCProjectAppDelegate*) [[UIApplication sharedApplication] delegate];

你可以设置值:

appDelegate.strUserID = @"Test";

获取价值:

NSString *strId = appDelegate.strUserID;

:)

【讨论】:

  • 应用委托用于应用级别的责任委托。不是任意代码/常量/设置的存储。
  • 您可以为全局变量创建一个头文件。您可以在该文件上定义全局变量。你以前想过这种方法吗?
猜你喜欢
  • 2017-12-11
  • 1970-01-01
  • 1970-01-01
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多