-1

目标是创建一个类,该类包含一组数据,供其他类在整个应用程序中使用。

我有这个 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 编程新手。所以可能我的方法是错误的?

4

2 回答 2

1

您忘记在“GlobalObjects”animals的方法中分配数组:init

self.animals = [[NSMutableArray alloc] init];

如果你不这样做,就是self.animals没有效果。niladdObject

由于您不使用 ARC,因此请记住在dealloc.

编辑:正如@H2CO3 和@Bastian 所注意到的,我忘记了我的ARC 前课程。self.animals所以在你的 init 方法中分配的正确方法是

self.animals = [[[NSMutableArray alloc] init] autorelease];

dealloc必须添加

self.animals = nil;

打电话之前[super dealloc]。我希望我现在就明白了!

于 2012-09-09T08:56:19.353 回答
1

是的,这是错误的——实例变量并不与本身相关,而是与类的特定实例相关联。这个问题的 Cocoa 标准解决方案是创建类的共享实例 - 而不是

elf.animalsData = [[[GlobalObjects alloc] init] autorelease];

elf.animalsData = [GlobalObjects sharedInstance];

并实现这样的+ sharedInstance方法:

+ (id)sharedInstance
{
    static shared = nil;
    if (shared == nil)
        shared = [[self alloc] init];

    return shared;
}

As @MartinR pointed out, you make another mistake: you don't create the array you're adding objects to - then it remains nil, cancelling out the effect of all method calls on itself. You have to alloc-init a mutable array for it in the - init method.

于 2012-09-09T08:56:49.513 回答