How to set array value and key in NSDictionary in iphone?

18,088

Solution 1

NSDictionary Class is immutable. You must convert to NSMutableDictionary.

Solution 2

If you are using XCode version 4.4 or later you can jus do this:

[dateArray addObject:dateString]; //NSMutablArray 
NSDictionary *myDictionary = @{ @"Date", dateArray };

Solution 3

You are using NSDictionary. You should use NSMutableDictionary. NSDictionary is immutable. If you want to use NSDictionary then use below method:

- (id)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
Share:
18,088
SampathKumar
Author by

SampathKumar

Senior iphone developer

Updated on June 04, 2022

Comments

  • SampathKumar
    SampathKumar almost 2 years

    Here i am using NSMutableArray to store date, then i tried to set key and assign ArrayValue in dictionary but the app crashed, please help me

    Thanks in ADvance

     Here i tried the code for your reference:
    
      [DateArray addObject:dateString]; //NSMutablArray 
      NSMutableDictionary *myDictionary =[[NSMutableDictionary alloc]init];         
      [myDictionary setObject:DateArray forKey:@"Date"]; //put array value and set key in NSDictionary.
    
  • deanWombourne
    deanWombourne almost 12 years
    myDictionary isn't mutable - you can't call addObject:forKey: on it.
  • Tripti Kumar
    Tripti Kumar almost 12 years
    check the question again before answering such a long answer.
  • deanWombourne
    deanWombourne almost 12 years
    Hang on, did you edit it and change the class names from immutable to mutable? You've changed the question that is being asked; do you know the original questioner? Edit is designed to make the question more correctly asked, not to 'fix' it - if you want to fix the code, answer the question!
  • Tripti Kumar
    Tripti Kumar almost 12 years
    Check out the name of Editor, don't blame me.
  • SampathKumar
    SampathKumar almost 12 years
    Now i used NSMutableDictionary to store date fine, then How to sort this dictionary, is it possible?
  • SampathKumar
    SampathKumar almost 12 years
    Now i used NSMutableDictionary to store date fine, then How to sort this dictionary, is it possible?
  • Apurv
    Apurv almost 12 years
    dictionary can not be sorted. You can sort an array. Also you should accept my answer because I have given it before.
  • bitmapdata.com
    bitmapdata.com almost 12 years
  • Paul.s
    Paul.s almost 12 years
    Your answer is pretty ambiguous. You have just given the method declaration without showing how to actually call it. This could very easily lead to any newbie using [NSDictionary initWithObjects:.... as this is where the method is declared.
  • Paul.s
    Paul.s almost 12 years
    There isn't actually any need to use a mutable dictionary here, instead just use the appropriate init method or new syntax.