Search code examples
iosobjective-cnsmutablearraynsarrayios10

Issue facing in isKindOfClass in iOS10


Recently I have upgraded XCode8 I am facing issue in isKindOfClass method this code is working till to iOS9 but in iOS10 suddenly [items isKindOfClass: [NSMutableArray class]] compiler not going in for loop condition may I know what is the reason?

NSMutableArray is child class of NSArray so when I am changing to [NSArray class] then it works fine so I am confuse why this change affect to NSMutableArray class which is child class of NSArray ?

     NSMutableArray *items = [jsonDictionary objectForKey:@"items"]; // Here i am taking response in NSMutableArray

     if ([items isKindOfClass: [NSMutableArray class]] && items != nil) // not working  {
         for (NSMutableDictionary *item in items)
         {
           // Rest of Code
         }
     }

This code works for me I m confuse the above code working until iOS9 when I change this below code then after working in iOS10:

     NSMutableArray *items = [jsonDictionary objectForKey:@"items"];

     if ([items isKindOfClass: [NSArray class]] && items != nil) // Changed to NSArray  {
         for (NSMutableDictionary *item in items)
         {
           // Rest of Code
         }
     }

Solution

  • From your comments, it seems that you actually have an NSArray, not an NSMutableArray, so isKindOfClass is working correctly. AFN will give immutable containers unless you specify otherwise, and this shouldn't be any different on iOS 10, so I am not sure why it was working previously.

    Rather than testing for a mutable array, it is probably simpler to create a mutable copy of whatever is there, this way you don't have to try and handle the "failure" condition gracefully:

    NSArray *items = [jsonDictionary objectForKey:@"items"];
    if (items != nil) {
         NSMutableArray *mutableItems = [items mutableCopy];
         for (NSMutableDictionary *item in mutableItems)
         {
           // Rest of Code
         }
     }
    

    Beware, unless you have specified the option to AFN to provide mutable containers, the dictionaries inside your items array will be NSDictionary not NSMutableDictionary, so you may need to make mutable copies of them.

    Of course, if you aren't mutating the array or the dictionary, then you can just u NSArray and NSDictionary regardless of whether you have a mutable or immutable object.