簡體   English   中英

目標C中的全局變量和對象。最佳方法是什么?

[英]Global variables and objects in Objective C. What is the best way?

我想為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

最好的方法是什么?還是應該使用單例模式,如下所示: 在Objective-C中使用全局變量

請分享想法?

在應用程序中使用全局變量的一種方法是:

您可以使用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;

:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM