我只是从Objective-C开始,我仍然很难做一些非常基本的事情。这就是我想要实现的目标 - 我需要创建一个类来保存应用程序的所有静态数据,我想可以用许多 NSString ** 数组表示这些数据,例如这个:
NSString *animalNames[NUM_ANIMALS] = {@"fox", @"wolf", @"elephant", @"giraffe"};
我希望能够从应用程序中的任何位置以静态方式访问这些数组。像这样:
StaticData.animalNames[1]
我将如何在@property、@interface、@synthesize和所有这些方面做到这一点?
我需要创建一个类来保存应用程序的所有静态数据
这是您正在谈论的一个例子。 这是一个基本的单例类,其中包含动物的静态数组。
#import <Foundation/Foundation.h>
@interface Foo:NSObject
+ (id)sharedFoo;
- (NSArray *)animals;
@end
@implementation Foo
static NSArray *animals;
+ (void)initialize {
animals = [NSArray arrayWithObjects:@"fox",@"wolf",@"giraffe",@"liger",nil];
}
+ (id)sharedFoo {
static dispatch_once_t pred;
static Foo *cSharedInstance = nil;
dispatch_once(&pred, ^{ cSharedInstance = [[Foo alloc] init]; });
return cSharedInstance;
}
- (NSArray *)animals {
return animals;
}
@end
int main(int argc, char *argv[]) {
NSLog(@"Animals = %@",[[Foo sharedFoo] animals]);
}
此应用程序将以下内容记录到控制台:
2012-10-08 10:01:46.814 无题[77085:707] 动物 = ( 狐狸 狼 长颈鹿 利格尔)
编辑:
如果您喜欢点语法/属性表示法,则可以在类接口中实现以下内容:
@property (readonly) NSArray *animals;
这会让你写:
[Foo sharedFoo].animals
等。