本文介绍了无法在单例中修改数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了一个单例(在 StackOverflow 的帮助下)但是当我尝试修改/访问数组listOfHeadings"时,似乎没有任何变化.我没有收到来自编译器或运行时的错误或警告.

I've set up a Singleton (with a lot of help from StackOverflow)but when I try to modify/access the array "listOfHeadings", it appears that nothing is changing.I get no errors or warnings from the compiler or when running.

我的 GlobalData.h 中有这个:

I've got this in my GlobalData.h:

#import <Foundation/Foundation.h>

@interface GlobalData : NSObject {    
    NSMutableArray *listOfHeadings;
}    
@property(nonatomic,retain)NSMutableArray *listOfHeadings;
+(GlobalData*)getInstance;  
@end

这是我的 GlobalData.m:

This is my GlobalData.m:

#import "GlobalData.h"

@implementation GlobalData
@synthesize listOfHeadings;
static GlobalData *instance; 

+(GlobalData *)getInstance{    
    @synchronized(self){    
        if(!instance){    
            instance= [[GlobalData alloc] init];
            instance.listOfHeadings=[[NSMutableArray alloc]init]; //EDIT: This line added to resolve problem
        }    
    }    
    return instance;    
}    
@end

我在 AppDelegate.m 中访问单例:

And I access the Singleton in my AppDelegate.m:

#import "GlobalData.h"
...inside didFinishLaunchingWithOptions...
    GlobalData *globDat=[GlobalData getInstance];
    [globDat.listOfHeadings addObject:@"Message Settings"]; 
    NSLog(@"appdel m array test %i",[globDat.listOfHeadings count]); // prints 0!

很明显我做错了什么 - 有人可以帮助指出我的错误吗?谢谢.

So clearly I'm doing something wrong - can some help point out my mistakes?Thanks.

推荐答案

listOfHeadings 是否有效并已实例化?

Is listOfHeadings valid and instantiated?

(注意:你可以在一个 nil 对象上调用方法而在 Obj-C 中没有错误!)

(Note: you CAN call methods on a nil object with no errors in Obj-C!)

这篇关于无法在单例中修改数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 09:15