【问题标题】:How to know that my array contains dictionary or not?如何知道我的数组是否包含字典?
【发布时间】:2016-11-13 00:34:19
【问题描述】:

我有一个这样的数组

   ( {
    GPSOdometerReading = "11843.6";
    "_id" =         {
        "$oid" = 5656e7175201edbb16a483f4;
    };
    acc = 0;
    )

那么如何知道我的数组是否包含字典呢?

谢谢。

【问题讨论】:

    标签: ios objective-c arrays dictionary


    【解决方案1】:

    您需要枚举数组并检查每个对象的类,如下所示

    BOOL isContainsDict = NO;
    for (id value in Array){
        if ([value isKindOfClass:[NSDictionary class]]){
            isContainsDict = YES;
            break; // end since you only want to know if the array contains an instance of dictionary. if it does no need to continue the loop just break and perform the process
          }
    }
    

    【讨论】:

    • 答案很好,很简短
    • isContainsDict 应该被初始化。
    【解决方案2】:

    您可以使用此代码:

    -(BOOL)arrayContainDictionary
    {
         for(int i=0; i<[array count];i++){
             if([array[i] isKindOfClass:[NSDictionary Dictionary]]){
                 return YES;
             }
         }
         return NO;
    }
    

    【讨论】:

    • 如果第一个对象不是 NSDictionary 而不进一步检查,这将返回 NO,返回 NO 应该在 forloop 之外。
    猜你喜欢
    • 2019-08-07
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多