Objective-C Tips & Trick - Prioregroup.com
[Objective-C] Remove observe notification and release all properties
       
back

//  Created by Danilo Priore on 09/16/12.
//  Copyright (c) 2012 Prioregroup.com. All rights reserved.
//
// Automatic remove observe notification, release object and set it nil for all properties.
//
- (void)deallocProperties
{
    Class class = [self class];
    unsigned int pCount;
    objc_property_t *properties = class_copyPropertyList(class, &pCount);
    
    for (unsigned int i = 0; i < pCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyAttributes = [[[NSString alloc] initWithUTF8String:property_getAttributes(property)] autorelease];
        NSArray *propertyAttributeArray = [propertyAttributes componentsSeparatedByString:@","];
        BOOL isRetained = NO;
        
        for (NSString *string in propertyAttributeArray) {
            isRetained = isRetained || [string isEqual:@"&"] || [string isEqual:@"C"];
            if (isRetained) break;
        }
        
        NSString *variableName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        if (variableName != nil) {
            [self removeObserver:self forKeyPath:variableName];
            
            if (isRetained) {
                Ivar ivar = class_getInstanceVariable(class, [variableName UTF8String]);
                id value = object_getIvar(self, ivar);
                
                if (value != nil) {
                    [value release];
                    object_setIvar(self, ivar, nil);
                }
            }
        }
    }
    
    free(properties);
}






Copyright © 1996-2018 Centro Studi Informatica di Danilo Priore. All rights reserved. P.I.10149810581.
prioregroup.com