开发者

Weird !=nil check issue

I have a UITableViewController which has a UIView* called errorView that is used to overlay an error message over the table view if a method fails to load web data.

In the init method, errorView is set to nil (0x0 in debugger).

In a load method, called at the 开发者_StackOverflow中文版end of init AND if a 'refresh' UIButton (on the errorView) is tapped, errorView is compared to nil, and removed from superview and released if it is not nil (Still shows 0x0 in debugger).

In the dealloc method, the same check is done before releasing; but for some reason the variable is never nil even though it hasn't been assigned (0xc000 in debugger) because the data failed method was never called. The app then crashes because it tries to dealloc a null pointer that is != nil.

Example:

-(id)init {
    errorView = nil;
    [self Load];
}

-(void)Load {
    if(errorView != nil) {
        [errorView removeFromSuperView];
        [errorView release];
        errorView = nil;
    }

    //Attempt to load data from web
}

-(void)dataFailedToLoad (e.g. UIWebView didFailLoadWithError) {
    errorView = [[UIView alloc] initWithFrame, etc];
    [self.tableView addSubview:errorView];
}

-(void)dealloc {
    if(errorView != nil)
        [errorView release]; //Always crashes because errorView is never nil even though it has been assigned nil?
}

I'm pulling hair out over this. The errorView variable IS NOT USED anywhere else but in these methods as described, and everything I can read into suggests it is the proper way to do it.


As a point of interest; sending a message to a nil object is not an error; a significant number of your checks are completely useless.

Exactly what is going on here is hard to point out without more information; if dataFailedToLoad actually is the only place where errorView is assigned, your code should work. However, it's failure indicates that something else is screwing your pooch.

Incidentally, a null pointer that != nil isn't a null pointer.


Just because you called init the view doesn't have to be initialized. You should use the standard method viewDidLoad to ensure that the view isn't nil.


Are you sure you are talking to the instance you think you are talking to?

I've seen quite a few SO questions that have boiled down to confusion between what the loading of an interface file (xib) instantiates and what the developer needs to instantiate.

I.e. do something like NSLog(@"%@ %p", self, self); in all the methods and make sure the address-- the instance-- is the same.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜