Dailycode.info

Short solution for short problems

Using nullable/nilable types with iOS

It's obvious that iOS doesn't support nilable or nullable(.Net) types. I started having problems becuase we have a .Net implementation (server side) where we have bool? So on client side it resulted in a YES/NO/N/A choice. In iOS its a Segmented Control that has these options. But when my Entities are converted to iOS objects, they result offcourse in simple types: bool. So this means that its by default no. How to solve this? I could change my objects on server side and regenerate them. But since I'm using the entity framework generation, I do not want to do this. Then my collegue pointed me in the good direction. Using partial classes on server side eventually did the trick. So by extending the base class and adding properties I got a working solution. I will describe it below with some points to pay attention to.

So on iOS site I want int in stead of bool. Int value 0 = YES, 1 = NO and 2 = null. To get this I created some methods on the .Net WCF services. Here is an example of the extension class I used:

public partial class GP_MES_F06ByOrder

{

    [DataMember]

    public int ICHolesNS

    {

        get

        {

            return GalvEntFunctions.GetIntFromBool(this.ICHoles);

        }

        set

        {

            this.ICHoles = GalvEntFunctions.GetBoolFromInt(value);

        }

    }

 

    [DataMember]

    public int ICDoubleWeldNS

    {

        get

        {

            return GalvEntFunctions.GetIntFromBool(this.ICDoubleWeld);

        }

        set

        {

            this.ICDoubleWeld = GalvEntFunctions.GetBoolFromInt(value);

        }

    }

 

The functions to convert the int to bool and bool to int I used:

public class GalvEntFunctions

{

    public static bool? GetBoolFromInt(int value)

    {

        switch (value)

        {

            case 0: return true;

            case 1: return false;

            default: return null;

        }

    }

 

    public static int GetIntFromBool(bool? value)

    {

        switch (value)

        {

            case true: return 0;

            case false: return 1;

            default: return 2;

        }

    }

}

Now these properties are available on you entities. Mind the name giving. Thats important. Because the serializer will serialize and deserialize in the order of the properties. So in my case cince I'm using it for iOS I added NS at the end to make sure this property is de/serialized after the original property. In my iOS client I only use the NS properties to get what I want.

Now you can use the default Entity generation without messing around in the code afterwards.

On iOS side I can now implement these nullable types very easy with my segmented controls:

    self.selOpeningHolesOK.selectedSegmentIndex = self.currentF06.ICHolesNS;

    self.selLoadingPosibilities.selectedSegmentIndex = self.currentF06.ICLoadingPos;