cateof
cateof

Reputation: 6768

Do I need to send release to my instance variable in the dealloc method? (iOS)

In my class dealloc method I have

- (void) dealloc
{
    [searchField release]; 
    [super dealloc];
}

Where searchField is defined in the class variables.

@interface SearchCell : UITableViewCell
{
    UISearchBar *searchField;
    id delegate;
}

The class is used with the following way:

if (indexPath.section == 0)
    {
        SearchCell *mycell = [[SearchCell alloc] init];
        [cell setDelegate:self];
        return [mycell autorelease];
    }

searchField is created here:

- (id) init
{
    self = [super initWithFrame:CGRectZero];

    [self create];

    return self;
}

- (void) create
{
    searchField = [[UISearchBar alloc] initWithFrame:CGRectZero];
    searchField.autocorrectionType = UITextAutocorrectionTypeNo;    
    [self addSubview:searchField];
}

Do I need to use [searchField release]; in my dealloc? The application crashes with message: "*[UISearchBar respondsToSelector:]: message sent to deallocated instance *".

Upvotes: 0

Views: 323

Answers (2)

Carl Veazey
Carl Veazey

Reputation: 18363

You need to be aware of object ownership rules. In manual retain & release environment (as opposed to ARC) the rules for Objective-C objects can be remembered with the acronym NARC.

If you have a reference to an object that you created fresh using new or alloc, or any object that you called retain on, or any object you created by calling copy or mutableCopy on another, or any object created by any methods that start with any of these names (e.g. newInstance), then you own that object and before you are deallocated you must release it.

But, if you didn't do any of those things, then you do not own that object, and must not release it. source

In your case - you don't show the code where you set the value searchField, but from the crash I'd imagine you never take ownership of the object. Show the code where you assign to searchField and we'll all know for sure. EDIT: You do take ownership by creating it with alloc. You need to keep the release there in dealloc. Is it being released from somewhere else? Or is the cell itself possibly getting overreleased?

Upvotes: 0

nullp01nter
nullp01nter

Reputation: 521

No, don't release it there. Since you return it with "autorelease", the next run through your event loop will automatically decrease the retain count.

When you finally hit your "dealloc" method, the retain count is already 0 and your app will raise an exception.

Upvotes: 1

Related Questions