Question

How can I store an uninitialized object in an NSDictionary?

I think I would do it like this, but I’m not certain that it’s a good approach:

 NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
                     [MyObject1 alloc], @"myObject1",
                     [MyObject2 alloc], @"myObject2"
                     , nil];

MyObject1 *object = [dict objectForKey:@"myObject1"];

[object init];

Any help would be appreciated.

Was it helpful?

Solution

What you need is to store mutable objects inside the dictionary. Doing this you will be able to modify them after the insertion, because an immutable dictionary doesn't allow to insert a new object.

If for "uninitialized" you mean that the object has only been created with alloc, without init, that's deprecable because init may return a different object from the one returned with alloc. So just store them like you're doing it, and when you need to modify them call the accessors:

NSDictionary *dict = @{ @"myObject1" : [MyObject1 new] , @"myObject2" : [MyObject2 new] };
dict[@"myObject1"].someProperty= someValue;

If your MyObject1 class is immutable, then you have to use a mutable dictionary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top