Search code examples
iosobjective-ckey-value-observing

Objective C - How To Keep Reference To Multiple Objects With Keys Just Like How NSMutableDictionary Works


I just learned how to make use of KVO, but only the basics. What I need to achieve is something like this:

I have a delegate call that passes a Speaker object.

- (void)onSpeakerFound:(Speaker *)speaker

Once I receive this Speaker in the UI part, from there I will assign observers for this object.

But, this is just for one speaker. What if I have multiple speakers to keep track of. I need to assign observers separately for those speakers and then at the same time I wish to keep their references for further updates to the values.

Each speaker could be updated from time to time. So when I notice that there is a change that happened on a speaker, I wish to access the reference to that speaker and update the values just like how NSMutableDictionary works.

NSMutableDictionary makes a copy of an object set to it so it will be a difference object if I get it again from the dictionary.

So, is there a class that allows me to keep track of an object by just keeping a reference only to that object without making a copy of it?

EDIT: A Test Made To Verify That When An Instantiated Object is Set in an NSMutableDictionary, The Instantiated Object is not referenced with the one set inside NSMutableDictionary.

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

    NSString *obj = @"initial value";
    NSString *key = @"key";

    [dict setObject:obj forKey:key];

    NSLog(@"Object is now %@", [dict objectForKey:key]);

    obj = @"changed value";

    NSLog(@"Object is now %@", [dict objectForKey:key]);
}

Log:

2016-07-26 21:04:58.759 AutoLayoutTest[49723:2144268] Object is now initial value
2016-07-26 21:04:58.761 AutoLayoutTest[49723:2144268] Object is now initial value

Solution

  • NSMutableDictionary makes a copy of an object set to it...

    That is not correct; it will add a reference to the object. It will be the same object referenced inside and outside the Objective-C collection.

    So, is there a class that allows me to keep track of an object...?

    Probably NSMutableSet if you just want a list of the objects. That will take care that you have a unique reference to each object, however you need to implement the methods hash and isEqual on those objects so they behave correctly. Otherwise NSMutableDictionary if you want fast look-up by key.