vendredi 31 juillet 2020

How to create an inline conditional assignment in Objective-C?

My Pet class has 2 properties: BOOL isHungry and NSNumber *age. I want to put the properties of Pet myPet into NSMutableDictionary *myMap.

This is my code is Java. I am trying to write an equivalent in Objective-C

myMap.put("isHungry", myPet == null ? null : myPet.isHungry);
myMap.put("age", myPet == null ? null : myPet.age);

This is my current Objective-C version:

[myMap addEntriesFromDictionary:@{
    @"isHungry" : myPet ? myPet.isHungry : (NSInteger)[NSNull null],
    @"age" : myPet ? myPet.age : [NSNull null],
}];

The error for the second line is the following:

Incompatible operand types ('int' and 'NSNull * _Nonnull')

The compiler stopped complaining about the first line when I added (NSInteger). If I put the same on the second line, the error goes away, but the compiler complains about the first line again:

Collection element of type 'long' is not an Objective-C object

I am a noob in Obj-C and I am totally lost. I would also like to know the best practice for Obj-C.

Aucun commentaire:

Enregistrer un commentaire