overriding release method

Member
Posts: 73
Joined: 2009.03
Post: #1
In one of my classes, I have added a release method. It goes something like this:

Code:
-(oneway void)release
{
  // Do some other stuff.

  [super release];
}

I know you're probably wondering what the "other stuff" is. Well, this class has a global NSMutableArray to keep a list of all objects of this type. Since the list does a "retain" on objects that are added, I have to remove the object from the list before dealloc will be called. So, I do that in my own release method first.

Is there anything wrong with doing this kind of thing?

[edit] I guess I found out for myself. The release call from the list recursively calls this release method, resulting in an infinite loop. I guess I'll have to use a different method of my own like "free". The only reason I didn't do that in the first place is because I am using these objects as properties with the "retain" attribute, so I only needed to set the property to nil to release it. Looks like I'll have to call my free method instead.
Quote this message in a reply
DoG
Moderator
Posts: 869
Joined: 2003.01
Post: #2
You should do this kinda thing in -dealloc, but not in -release. I suggest you go over Cocoa Memory Management again Smile
Quote this message in a reply
Member
Posts: 73
Joined: 2009.03
Post: #3
It's not possible to do it in dealloc because dealloc would never get called since the object is still retained in the array. It's ok, I'm using a free method instead, which handles the release and removes it from the array.
Quote this message in a reply
Moderator
Posts: 133
Joined: 2008.05
Post: #4
This is most likely what you want: (Trivia: NSPointerArray is not available on the iPhone.)
Code:
//
//  TrackedObject.m
//  WeakTest
//
//  Created by Joe Conway on 11/26/09.
//  Copyright 2009 Big Nerd Ranch. All rights reserved.
//

#import "TrackedObject.h"

static CFMutableArrayRef TrackedObjectList = NULL;

@implementation TrackedObject
+ (void)initialize
{
    CFArrayCallBacks callbacks =
    {
        0,
        NULL,
        NULL,
        NULL,
        NULL
    };
    TrackedObjectList = CFArrayCreateMutable(NULL, 0, &callbacks);    
}
+ (id)allocWithZone:(NSZone *)zone
{
    id obj = [super allocWithZone:zone];
        if(obj)
          CFArrayAppendValue(TrackedObjectList, obj);
    return obj;
}
+ (NSArray *)allTrackedObjects
{
    return (NSArray *)TrackedObjectList;
}
- (void)dealloc
{
    int len = CFArrayGetCount(TrackedObjectList);
    int idx = CFArrayGetFirstIndexOfValue(TrackedObjectList, CFRangeMake(0, len), self);
    CFArrayRemoveValueAtIndex(TrackedObjectList, idx);
    [super dealloc];
}
@end
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Overriding protocol methods - possible? muleskinner 1 2,105 Apr 24, 2009 05:54 AM
Last Post: ThemsAllTook