Xamarin ios - 我如何检查零值

时间:2015-07-16 17:01:16

标签: xamarin null

我想在将对象插入nsdictionary之前检查nil(非null)对象。我该如何检查?

public override void DidReceiveData (MCSession session, NSData data, MCPeerID peerID)
        {
            if (data != null && peerID != null) {
                NSObject[] ObjectsArray = new NSObject[]{ data, peerID };
                NSObject[] KeysArray = new NSObject[]{ new NSString ("data"), new NSString ("peer") };
                NSDictionary dict = NSDictionary.FromObjectsAndKeys (ObjectsArray, KeysArray);
                NSNotificationCenter.DefaultCenter.PostNotificationName (MultiPeerMasterController.MCDidReceiveDataNotification, null, dict);
            }
        }

1 个答案:

答案 0 :(得分:1)

您应该使用Dictionary<TKey, TValue>object代替NSObject和NSDictionary。

示例:

object[] ObjectsArray = new[] { data1, data2 };

string[] KeysArray = new[] {"data1", "data2"};

var dictionary = new Dictionary<string, object>();

for (int index = 0; index < myInts.Length; index++)
{
    var object = ObjectsArray[index];

    // check for null here before adding it to the dictionary
    if (object != null)
    {
       dictionary.Add(KeysArray[index], ObjectsArray[index]);
    }
}

//convert to NSDictionary
var nsDictionary = NSDictionary.FromObjectsAndKeys (dict.Keys.ToArray (), dict.Values.ToArray ());

您需要添加using System.Linq;才能获得ToArray()方法

- 编辑 -

如果要检查Objective-C集合中的nil值,则需要使用NSNullhttps://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNull_Class/

在Xamarin中,您可以通过检查NSNull.Null的值来执行此操作 http://developer.xamarin.com/api/type/MonoTouch.Foundation.NSNull/