How to make a Global Array?

旧街凉风 提交于 2019-12-04 07:10:57

Just a general programming suggestion--don't share an array. You have no control over it and it will be virtually impossible to trace if something changes it at a time and in a way you aren't expecting.

Instead, create an object with the array inside it and make that object a singleton (or better yet, make a factory for it).

Whenever you want to modify your array, call methods on the object to do so. If you do this, I bet you will find a lot of redundant code you can factor into this object (for instance, searching the array for a value--make a "search" method in the object instead and pass in a value).

It may seem like a lot of work you shouldn't have to do, but you'll find it's fairly fun work, and you should find that you DO have to do it once you see how much code belongs in this object...

Just add the array as a property of the application delegate, and access it like:

[[UIApplication sharedApplication] myArray];

The two (main) ways of making an array global are separate -- either you have a class with a method

static NSMutableArray *foo;
+(NSMutableArray *)foo {
    return foo;
}

(in the .m file) with the static piece NOT in the header file, or just

static extern NSMutableArray * myGlobalArray;

with out the singleton wrapper (which I think is better as it saves you from having an extra bit of unnecessary code)

Either way, it is still a bad practice that I would try to avoid.

In general, the presence of a "Globals.h" file is a bad smell that there's an antipattern at work.

I would even advise against Bill K's advice and not use a Singleton pattern at all.

Instead, create the array in your app delegate, and pass it to your root view controller(s), and along the hierarchy to the components that need access to it.

This is what I was looking for:

http://derekneely.com/tag/app-delegate/

Thank you for pointing me in the right direction!

#import <Foundation/Foundation.h>

static extern NSMutableArray * myGlobalArray;

@interface Globals : NSObject {
}


@end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!