iPhone, I need to reuse an NSArray which has constant values in different views, how?
I have the following array.
NSArray *arrayDisplay = [[NSArray alloc] initWithObjects:@"Daily",
@"Weekly", @"Monthly", nil];
I need to use it in two views, I'm concerned 开发者_StackOverflowthat I may make changes and forget to change the other in the future. So I'd like to declare it once and reuse it.
How should I do this?
You can keep it as a property in a common object such as the application delegate.
Assuming its nonatomic,retain type property then access it like:
myAppDelegate *del = [[UIApplication sharedApplication] delegate];
del.arrayDisplay = [NSArray arrayWithObjects:@"Daily",@"Weekly", @"Monthly", nil];
Although if you plan on changing it you might want an NSMutableArray.
Consider writing a class method or even a C function that lazily creates the array. For example, here's a class method that does what you want:
+ (NSArray *)frequencyChoices
{
static NSArray *choices;
if (choices == nil)
{
choices = [[NSArray alloc] initWithObjects:
@"Daily", @"Weekly", @"Monthly", nil];
}
return choices;
}
Writing the same functionality as a C function makes it even more general:
NSArray *frequencyChoices(void)
{
static NSArray *choices;
if (choices == nil)
{
choices = [[NSArray alloc] initWithObjects:
@"Daily", @"Weekly", @"Monthly", nil];
}
return choices;
}
The advantage of a class method though, is that you could override it in a subclass if that might ever prove handy.
If your application is simple, consider the Singleton model where the data you are accessing are accessible through the global instance of the singleton. link text
Rather than using a Singleton approach, consider determining which object in your app's object hierarchy should own this array, and then pass that reference down to where it's needed (see: dependency injection).
You could save the array as a plist in your project and load it in each place where it's needed with
NSArray *arrayDisplay = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"myArrayName" ofType:@"plist"]];
This will work as long as you do not need to change the values in both place while the program is actually running.
If you don't mind global variables, you can instantiate them at load time:
@interface FooClass : ... {
...
}
static NSArray * FooClass_timescale;
@end
@implementation FooClass
+(void)load {
FooClass_timescale = [[NSArray alloc] initWithObjects:@"Daily", @"Weekly", @"Monthly", nil];
}
@end
I prefer doing this when there are a pile of things I want to instantiate (e.g. colours for a theme/skin/brand/whatever), since it's shorter than writing a function to return them. Of course, it's possible to accidentally modify the global variable, but I've never managed this (usually I just forget to retain).
精彩评论