目标是创建一个类,该类包含一组数据,供其他类在整个应用程序中使用。
我有这个 GlobalObject.h
它声明了用于存储数据的数组。
#import <Foundation/Foundation.h>
@interface GlobalObjects : NSObject
@property (retain) NSMutableArray *animals;
-(id)init;
@end
我有这个 GlobalObject.m。
它包含 NSDictionary 数据并存储到数组中。
#import <Foundation/Foundation.h>
@interface GlobalObjects : NSObject
@property (retain) NSMutableArray *animals;
-(id)init;
@end
#import "GlobalObjects.h"
@implementation GlobalObjects
@synthesize animals;
-(id)init{
self = [super init];
if (self) {
// Define the data
NSArray *imagesValue = [[[NSArray alloc] initWithObjects:@"dog.wav",@"cat.png",@"bird.png",nil] autorelease];
NSArray *audioValue =[[[NSArray alloc] initWithObjects:@"dog.wav",@"cat.wav",@"bird.wav",nil] autorelease];
NSArray *descriptionValue = [[[NSArray alloc] initWithObjects:@"Dog",@"Cat",@"Bird",nil] autorelease];
// Store to array
for (int i=0; i<8; i++) {
NSDictionary *tempArr = [NSDictionary dictionaryWithObjectsAndKeys:[imagesValue objectAtIndex:i],@"image", [audioValue objectAtIndex:i],@"audio", [descriptionValue objectAtIndex:i], @"description", nil];
[self.animals addObject:tempArr];
}
}
return self;
}
@end
我是这样称呼它的。
// someOtherClass.h
#import "GlobalObjects.h"
@property (nonatomic, retain) GlobalObjects *animalsData;
// someOtherClass.m
@synthesize animalsData;
self.animalsData = [[[GlobalObjects alloc] init] autorelease];
NSLog(@"Global Object %@ ",self.animalsData.animals);
现在的问题是,当我在另一个类中调用这个数组时,它总是返回 null。
我是 iOS 编程新手。所以可能我的方法是错误的?