如何在 Objective-C 中声明全局变量?
// MyClass.h
@interface MyClass : NSObject
{
NSDictionary *dictobj;
}
@end
//MyClass.m
@implementation MyClass
-(void)applicationDiDFinishlaunching:(UIApplication *)application
{
}
-(void)methodA
{
// Here i need to add objects into the dictionary
}
-(void)methodB
{
//here i need to retrive the key and objects of Dictionary into array
}
我的问题是,因为 methodA 和 methodB 都使用 NSDictionary 对象 [即 dictobj] 我应该在哪个方法中编写此代码:
dictobj = [[NSDictionary alloc]init];
我不能在这两种方法中执行两次,因此如何总体上执行它?
// MyClass.h
@interface MyClass : NSObject
{
NSDictionary *dictobj;
}
@end
//MyClass.m
@implementation MyClass
-(void)applicationDiDFinishlaunching:(UIApplication *)application
{
}
-(void)methodA
{
// Here i need to add objects into the dictionary
}
-(void)methodB
{
//here i need to retrive the key and objects of Dictionary into array
}
My question is since both methodA and methodB are using the NSDictionary object [i.e dictobj] In which method should i write this code:
dictobj = [[NSDictionary alloc]init];
I can't do it twice in both methods, hence how to do it golbally?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,如果您需要修改字典的内容,它应该是可变的:
您通常在指定的初始化程序中创建像 dictobj 这样的实例变量,如下所示:
并在 -dealloc 中释放内存:
您可以在您的目录中的任何位置访问实例变量。实例实现(与类方法相对):
First of all, if you need to modify contents of the dictionary, it should be mutable:
You typically create instance variables like dictobj in the designated initializer like this:
and free the memory in -dealloc:
You can access your instance variables anywhere in your instance implementation (as opposed to class methods):