0

当我的应用程序启动并设置一些全局属性时,我创建了一个全局对象。我稍后会从 ViewController 中引用其中一个属性。有时它很好,有时整个应用程序崩溃。

我如何告诉 ARC 不要自动释放我的对象?

#import "Global.h"
#import "GeneralHelper.h"

@implementation Global

@synthesize orangeClr;

Global* glob;

+(void) AppInit
{    
    glob = [[Global alloc] init];
    [glob setStyles];
}
-(void) setStyles
{
    orangeClr =  [GeneralHelper colorFromRGBA:255 :102 :0 :1];
}

+(Global*) get { return glob; }


@end
4

3 回答 3

1

另一种使用单一调度编写单例的方法:

+(Global *)sharedManager {
    static dispatch_once_t pred;
    static Global *shared = nil;

    dispatch_once(&pred, ^{
        shared = [[Global alloc] init];
    });
    return shared;
}
于 2012-08-24T08:08:48.817 回答
0

Better you have singleton instance na, i.e.,

static Global* glob = nil;

+(Global*) SharedInstance
{   
    if (!glob)
    {
        glob = [[Global alloc] init];
        [glob setStyles];
    }
    return glob;
}

Now this makes sure that only one instance is there through out the app, and you can release this when app is about to terminate. (It is one of the design pattern) You can refer to this class property from any viewController, and only for the first time it will allocate and set style. other times it will just use previous reference. Note it returns Global reference. Now your global class can provide many functionality and that functions will be in object level, not class level.

Eg:

- (void) someFunction;

can be called as

[[Global SharedInstance] someFunction];

And dont forget to include Global.h in other viewControllers

于 2012-08-24T07:08:48.407 回答
0

使变量变强,如果变量名未在文件外部使用,您也应该将其声明为静态。

__strong static Global* glob;
于 2012-08-24T01:39:08.797 回答