Tuesday, July 3, 2012

Set Custom object as key of NSDictionary


1.  To set an object of our Custom class as key of NSDictionary, we should implement NSCopying and override isEqual, hash methosds.

2. If we are setting the object of or custom class, we should use setObject: method of NSDictionary instead of setValue:
e.g:
CustomObj *objkey = [CustomObj getKeyWithModule:@"1" AndType:@"Open"];

[dictionary setObject:anotherObj forKey:objkey];


3. If you are using your dictionary to sort data using NSSortDescriptor, We should use string value of object instead of object and can use setValue: or setObject: method of NSDictionary.
e.g:
CustomObj *obj1 = [CustomObj getKeyWithModule:@"1" AndType:@"Open"];

NSString *myKey = [obj1 getStringValue];

[dictionary setObject:anotherObj forKey:keyy];

//or

[dictionary setValue:anotherObj forKey:keyy]; 


 
Following is the .h and .m class of CustomObj

-------------------------.h-----------------
#import <Foundation/Foundation.h>
@interface CustomObj : NSObject <NSCopying>
{
    @private
  
    NSString *module;
    NSString *type;
  
}
@property (nonatomic, retain) NSString *module;
@property (nonatomic, retain) NSString *type;


+(CustomObj *)getKeyWithModule:(NSString *)module
AndType:(NSString *)type;
- (NSString *) getStringValue;

@end 


-------------------------.m-----------------

 #import "CustomObj.h"

@interface CustomObj (Private)

-(id)initWithModule:(NSString *)module AndType:(NSString *)tag;
- (BOOL)isEqualToObject:(CustomObj *)otherObj;

@end


@implementation CustomObj

@synthesize module, type;


+(CustomObj *)getKeyWithModule:(NSString *)module AndXmlTag:(NSString *)type {
   
   
    CustomObj *qsKey = [[CustomObj alloc] initWithModule:module AndType:type];
    return [qsKey autorelease];
}

-(id)initWithModule:(NSString *)module AndType:(NSString *)tag {
   
    self = [super init];
    if (self) {
       
        self.module = module;
        self.type = tag;
    }
    return self;
}

- (id)copyWithZone:(NSZone *)zone {
   
    CustomObj *copy = [[[self class] allocWithZone:zone] initWithModule:self.module AndType:self.type];
   
    return copy;
}

- (BOOL)isEqual:(id)other {
       
    if (other == self) {
        return YES;
    }
   
    else if (other  && [other isKindOfClass:[self class]]) {
       
        return [self isEqualToObject:other];
    }
   
    else {
        return NO;
    }
}

- (BOOL)isEqualToObject:(CustomObj *)otherObj {
       
    if ([otherObj.module isEqualToString:self.module] && [otherObj.type isEqualToString:self.type]){
        return YES;
    }

    else {
        return NO;
    }
}

- (NSString *) getStringValue{
   
    return [NSString stringWithFormat:@"%@-%@",module, type];
   
}

-(NSUInteger) hash;
{
    //return [self getStringValue] hash];
    return [type hash];
}
- (void) dealloc{
   
    [type release];
    [module release];
    [super dealloc];
}



@end

No comments:

Post a Comment