0

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.

Ben Klein
  • 1,719
  • 3
  • 18
  • 41
Pelish8
  • 109
  • 2
  • 9
  • Why would you even want to do that? – omz Jan 12 '13 at 11:47
  • Like omz, it's hard to see the point of this. You basically want to store a bunch of nils for some keys? This isn't allowed and as stated makes very little sense. Perhaps you are approaching whatever task you trying to solve form the wrong end. What is your ultimate goal? – T. Benjamin Larsen Jan 12 '13 at 12:09
  • I need to have a Dictionary of Object that will implement the same protocol but implementation of method will be different, and key will be parameter that will tell what object to use. – Pelish8 Jan 12 '13 at 12:10
  • You're missing a bracket. – Ramy Al Zuhouri Jan 12 '13 at 12:31
  • 1
    To emphasize; you should *never* allocate an instance of a class without immediately initializing it and you should **always** assume that the return value from the initializer may be different than the return value from the allocator. – bbum Jan 12 '13 at 19:00

1 Answers1

3

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.

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187