This should be straightforward but something is preventing me from filtering an array of custom objects by NSNumber using NSPredicate. Perhaps it has something to do with the datatype when converting from JSON but I can't figure it out.
I download data from a JSON in an array of custom Objects that look like:
{"hid":"47","public":"1"}
The code to parse the JSON looks like:
if (feedElement[@"public"] && ![feedElement[@"public"] isEqual:[NSNull null]]) {
newMyObject.pub = feedElement[@"public"]== nil ? @"0" : feedElement[@"public"];}
The object looks like:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MyObject : NSObject
@property (nonatomic, retain) NSNumber * hid;
@property (nonatomic, retain) NSNumber * pub;
@end
NS_ASSUME_NONNULL_END
The objects are placed in an NSArray * myObjects
My NSPredicate and filter code looks like:
NSPredicate *pubPred = [NSPredicate predicateWithFormat:@"pub == 1"];
NSArray *filteredArray = [myObjects filteredArrayUsingPredicate:pubPred];
When I log [myObjects valueForKey:@"pub"], it logs as 1,1,1, etc. so I know that the values for pub are all 1 however the resulting filteredArray is empty.
What could be wrong with my code?
Thanks for any suggestions.
Edit: I changed public to pub in the object in case public was a reserved word but it did not change anything
With sample code :
{"hid":"47","public":"1"}In case of
publicvalue is present in JSON, you'll setpubproperty withfeedElement[@"public"], which means, it will be @"1" (with the sample), which means you'll put aNSString.In case of
publicvalue is present in JSON, you'll setpubproperty with @"0" which means you'll put aNSString.It doesn't matter if it's declared
@property (nonatomic, retain) NSNumber * pub;, you are setting aNSString, not aNSNumber.Want some code testing?
And
Output:
You can state: "Yeah, but you have a warning in
[[MyObject alloc] initWithPub:@"1" andHID:@"2"]:Incompatible pointer types sending 'NSString *' to parameter of type 'NSNumber *', yes, I have. You should have it too.In fact, you'll have it too if you wrote your ternary if :
What about using this to your code to check:
You should get a
-[__NSCFConstantString stringValue]: unrecognized selector sent to instanceerror, because it's really aNSString, not aNSNumber.Solutions:
You need to fix your parsing, or change the type of property in
MyObject.With keeping the property as a
NSNumber: