简体   繁体   中英

Object released too soon using ARC on iOS 5?

I created a class AppSettings containing booleans:

#import <Foundation/Foundation.h>

@interface AppSettings : NSObject{

bool bip10secCountdown;
bool jv10secCountdown;
bool jv30secAlert;
bool jv1minAlert;
bool jvp5minAlert;

}

@property bool bip10secCountdown;
@property bool jv10secCountdown;
@property bool jv30secAlert;
@property bool jv1minAlert;
@property bool jv5minAlert;

@end

And the implementation:

#import "AppSettings.h"

@implementation AppSettings

@synthesize bip10secCountdown, jv10secCountdown, jv30secAlert, jv1minAlert, jv5minAlert;


- (id)init
{
    self = [super init];
    if (self){
    }
    return self;

}

@end

Then I'm trying to use this class in my main class but after initializing the object in the viewDidLoad, when I want to use it again it appears as null.. So I guess it's released too early. I'm using ARC so I don't manually manage the memory. Am I doing something wrong?

The declaration in the main class:

AppSettings *appSettings;


}

@property(nonatomic)bool activated;
@property (nonatomic, strong) AppSettings *appSettings;

And the implementation:

@synthetize appSettings
...
- (void)viewDidLoad
{
    // Initialize the model
    self.appSettings = [[AppSettings alloc]init];

NSLog(@"appSettings = %@",self.appSettings);

The first output is OK. But then when I try to access appSettings from another method in the Main class, the appSettings is (null)

Thank you for your help.

The view has most likely unloaded, or your view controller has been released. Try moving the initialization code to the method where your view controller is initiated(- (id)initWithNibName: bundle:)

Instead of:

@property (nonatomic, strong) AppSettings *appSettings;

Try:

@property (nonatomic, retain) AppSettings *appSettings;

And I'd recommend to make your AppSettings as a Singleton-class.

When you say you initialise the view contoller in AppDelegate I presume you mean MyViewController *theView = [[MyViewController alloc] init]; or something like that. That will be your first view and you should initialise AppSettings in viewDidLoad of MyViewController, not the AppDelegate.

demon9733 suggestion regarding making AppSettings a singleton is a good one as you will be able to easily access your settings from anywhere in the app.

Also verify whether ARC is being used for MyViewController (or whatever it might be)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM