Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 311 Vote(s) - 3.61 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to check if an NSDictionary or NSMutableDictionary contains a key?

#11
if ([MyDictionary objectForKey:MyKey]) {
// "Key Exist"
}
Reply

#12
Using Swift, it would be:

if myDic[KEY] != nil {
// key exists
}
Reply

#13
Yes. This kind of errors are very common and lead to app crash. So I use to add NSDictionary in each project as below:

//.h file code :



@interface NSDictionary (AppDictionary)

- (id)objectForKeyNotNull : (id)key;

@end



//.m file code is as below

#import "NSDictionary+WKDictionary.h"

@implementation NSDictionary (WKDictionary)

- (id)objectForKeyNotNull:(id)key {

id object = [self objectForKey:key];
if (object == [NSNull null])
return nil;

return object;
}

@end

In code you can use as below:

NSStrting *testString = [dict objectForKeyNotNull:@"blah"];
Reply

#14
As Adirael suggested `objectForKey` to check key existance but When you call `objectForKey`in nullable dictionary, app gets crashed so I fixed this from following way.

- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
id object = dictionary;

if (dictionary && (object != [NSNull null])) {
self.name = [dictionary objectForKey:@"name"];
self.age = [dictionary objectForKey:@"age"];
}
return self;
}
Reply

#15


**Solution for swift 4.2**

So, if you just want to answer the question whether the dictionary contains the key, ask:

let keyExists = dict[key] != nil



If you want the value and you know the dictionary contains the key, say:

let val = dict[key]!

But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like `if let`:

if let val = dict[key] {
// now val is not nil and the Optional has been unwrapped, so use it
}
Reply

#16
if ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
//do something if doesn't exist
}

This is for nested dictionary structure
Reply

#17
<strike>

if ([[dictionary allKeys] containsObject:key]) {
// contains key
/* Don't use this solution. Look for more details in comments. */
}

</strike>

or

if ([dictionary objectForKey:key]) {
// contains object
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through