开发者

Objective-C : Member variable is losing reference between method calls

开发者 https://www.devze.com 2022-12-25 06:57 出处:网络
I\'ve been having with an objective-c class which appears to be losing its pointer reference between methods of the same class.

I've been having with an objective-c class which appears to be losing its pointer reference between methods of the same class.

In the MyTableViewController.h file, I declare:

@interface SettingsTableViewController : UITableViewController <UITextFieldDelegate>{
    OCRAppDelegate *delegate;
}

MyTableViewController.m file

- (id) init {
    self = [ super initWithStyle: UITableViewStyleGrouped ];
    delegate = [(OCRAppDelegate *)[[UIApplication sharedApplication] delegate] retain];
}

The problem is when the "MyTableViewController"开发者_JAVA百科 view appears again and a different method is executed within that same class, the delegate pointer (which was assigned during the init method) is no longer there. I tried to retain, but to no avail.

Would anyone know why this is, it seems like perhaps it is a fundamental Objective-C issue which I am missing.

Appreciate your help.

Thanks, Winston


The fact that the init method doesn't return anything might be the root of the problem - it has to return 'self'.

- (id) init {
    if (self = [super initWithStyle:UITableViewStyleGrouped]) {
        delegate = [(OCRAppDelegate *)[[UIApplication sharedApplication] delegate] retain];
    }
    return self;
}


When you say it's no longer there, what do you mean? What has its value changed to?

If the value is 0x0 (i.e. nil) either something changed it to nil or it always was nil. Have you checked that it is not nil when you assign it? Perhaps with an NSLog statement.

I suspect that, since it works in the viewWillAppear method, but not in the init method, the app delegate has not been initialized at the point init method is called so you are actually setting it to nil.


I think I may have found the answer.

For any initializations for the class, it should be done in ViewDidLoad. Prior to this, I believe that in the init method, the class is has not been fully set up.

What is interesting is for all my other views, the ViewDidLoad is called when the view is about to be loaded so all my variables/pointers exist. However, in the one class above, the viewdidload method is called very early on, and the delegate pointer back to the app delegate has not been fully set up.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号