在iPhone应用程序中保留全局变量的最佳方法 [英] The best way to keep global variables in iPhone app

查看:98
本文介绍了在iPhone应用程序中保留全局变量的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iPhone的新手,所以想问一下,保持全局变量和常量可以被许多类访问的最好方法是什么?



我应该让他们保留在应用程序委托中还是有一种更好的方式,我不知道?

谢谢

解决方案

将它们保留在应用程序委托中是一种解决方案,但将所有内容都推送到目标类对于常量,您可以简单地创建头文件并使用 #define const ,然后将头文件包含在需要常量的地方。



对于全局变量,您可以创建单身人士课程 static 变量。有很多宏可以合成类的单例。以下是Google Toolbox for Mac的一个例子:

  // 
// GTMObjectSingleton.h
/ /宏来实现单身
//
的方法//版权所有2005-2008 Google Inc.
//
//根据Apache许可证版本2.0(执照);您可能不会
//使用此文件,除非符合许可证。您可以在
//
处获得许可证的复制
// // http://www.apache.org/licenses/LICENSE-2.0
//
//除非适用法律要求或书面同意,否则根据许可证分发的软件
以原样为基础发布,不含
//任何类型的保证或条件,无论是明示还是暗示。请参阅
//许可证,以获取在
//许可证下管理权限和限制的特定语言的许可证。
//

#define _GTMDevAssert(condition,...)\
do {\
if(!(condition)){\
[[NSAssertionHandler currentHandler] \
handleFailureInFunction:[NSString stringWithUTF8String:__ PRETTY_FUNCTION__] \
file:[NSString stringWithUTF8String:__ FILE__] \
lineNumber:__ LINE__ \
描述:__ VA_ARGS__]; \
} \
} while(0)


///这个宏实现了构建安全单例所需的各种方法。
//
///这个单例模式取自:
/// http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/chapter_3_section_10.html
///
///示例用法:
///
/// GTMOBJECT_SINGLETON_BOILERPLATE(SomeUsefulManager,sharedSomeUsefulManager)
///(不带尾随分号)
///
#define GTMOBJECT_SINGLETON_BOILERPLATE(_object_name_,_shared_obj_name_)\
static _object_name_ * z ## _ shared_obj_name_ = nil; \
+(_object_name_ *)_ shared_obj_name_ {\
@synchronized(self){\
if(z ## _ shared_obj_name_ == nil){\
/ *请注意,'self'可能与_object_name_ * / \
/ *在allocWithZone中完成的第一次分配不同,但如果init失败,我们必须重新分配* / \
z ## _ shared_obj_name_ = [[self alloc] init]; \
_GTMDevAssert((z ## _ shared_obj_name_!= nil),@没有捕获单例分配); \
} \
} \
return z ## _ shared_obj_name_; \
} \
+(id)allocWithZone:(NSZone *)zone {\
@synchronized(self){\
if(z ## _ shared_obj_name_ = =无){\
z ## _ shared_obj_name_ = [super allocWithZone:zone]; \
return z ## _ shared_obj_name_; \
} \
} \
\
/ *我们无法返回共享实例,因为它已被初始化* / \
_GTMDevAssert(NO,@使用单例API,而不是alloc + init); \
返回零; \
} \
- (id)retain {\
return self; \
} \
- (NSUInteger)retainCount {\
return NSUIntegerMax; \
} \
- (void)release {\
} \
- (id)autorelease {\
return self; \
} \
- (id)copyWithZone:(NSZone *)zone {\
return self; \
}


I'm new to iPhone development so want to ask, what is the best way to keep global variables and constants which can be accessed by many classes?

Shall I keep them in app delegate or there is a better way which I don't know?

Thanks

解决方案

Keeping them in the app delegate is one solution, though it's not particularly elegant to shove everything into a class whose purpose is really to respond to events related to the application.

For constants, you can simply create header files and use #define or const, then include the header files wherever you need the constants.

For global variables, you can create a singleton class with static variables. There are a lot of macros out there that can synthesize singletons for classes. Here's an example from the Google Toolbox for Mac:

//
//  GTMObjectSingleton.h
//  Macro to implement methods for a singleton
//
//  Copyright 2005-2008 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not
//  use this file except in compliance with the License.  You may obtain a copy
//  of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
//  License for the specific language governing permissions and limitations under
//  the License.
//

#define _GTMDevAssert(condition, ...)                                       \
do {                                                                      \
if (!(condition)) {                                                     \
[[NSAssertionHandler currentHandler]                                  \
handleFailureInFunction:[NSString stringWithUTF8String:__PRETTY_FUNCTION__] \
file:[NSString stringWithUTF8String:__FILE__]  \
lineNumber:__LINE__                                  \
description:__VA_ARGS__];                             \
}                                                                       \
} while(0)


/// This macro implements the various methods needed to make a safe singleton.
//
/// This Singleton pattern was taken from:
/// http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/chapter_3_section_10.html
///
/// Sample usage:
///
/// GTMOBJECT_SINGLETON_BOILERPLATE(SomeUsefulManager, sharedSomeUsefulManager)
/// (with no trailing semicolon)
///
#define GTMOBJECT_SINGLETON_BOILERPLATE(_object_name_, _shared_obj_name_) \
static _object_name_ *z##_shared_obj_name_ = nil;  \
+ (_object_name_ *)_shared_obj_name_ {             \
@synchronized(self) {                            \
if (z##_shared_obj_name_ == nil) {             \
/* Note that 'self' may not be the same as _object_name_ */                               \
/* first assignment done in allocWithZone but we must reassign in case init fails */      \
z##_shared_obj_name_ = [[self alloc] init];                                               \
_GTMDevAssert((z##_shared_obj_name_ != nil), @"didn't catch singleton allocation");       \
}                                              \
}                                                \
return z##_shared_obj_name_;                     \
}                                                  \
+ (id)allocWithZone:(NSZone *)zone {               \
@synchronized(self) {                            \
if (z##_shared_obj_name_ == nil) {             \
z##_shared_obj_name_ = [super allocWithZone:zone]; \
return z##_shared_obj_name_;                 \
}                                              \
}                                                \
\
/* We can't return the shared instance, because it's been init'd */ \
_GTMDevAssert(NO, @"use the singleton API, not alloc+init");        \
return nil;                                      \
}                                                  \
- (id)retain {                                     \
return self;                                     \
}                                                  \
- (NSUInteger)retainCount {                        \
return NSUIntegerMax;                            \
}                                                  \
- (void)release {                                  \
}                                                  \
- (id)autorelease {                                \
return self;                                     \
}                                                  \
- (id)copyWithZone:(NSZone *)zone {                \
return self;                                     \
}

这篇关于在iPhone应用程序中保留全局变量的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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