Home > Enterprise >  Xamarin iOS - Why Can't I Iterate or Fetch by Index on an NSArray?
Xamarin iOS - Why Can't I Iterate or Fetch by Index on an NSArray?

Time:11-29

I am trying to either iterate over an NSArray in Xamarin, or fetch items by index as follows :

  try
    {  
        NSData value = (NSData)NSUserDefaults.StandardUserDefaults["accounts"];
        NSKeyedUnarchiver unarchiver = new NSKeyedUnarchiver(value);

        NSArray valuesDictionary = (NSArray)NSKeyedUnarchiver.UnarchiveObject(value);

        foreach (var x in valuesDictionary)
        {

        }


        if (valuesDictionary != null)
        {
            var accountList = new List<Account>();

            int numberOfOrgs = (int)valuesDictionary.Count;

            for (int x = 0; x < numberOfOrgs; x  )
            {
                var org = valuesDictionary[x];
            }
        }

However the compiler throws errors both for the iteration and the indexing.

   foreach (var x in valuesDictionary)
    {

    }

errors with "foreach statement cannot operate on variables of type 'NSArray' because 'NSArray' does not contain a public instance or extension definition for 'GetEnumerator'"

and

var org = valuesDictionary[x];

errors with "Cannot apply indexing to a type of NSArray".

Can anyone suggest why this is ? In Objective C I think I'd be able to do both of these things.

Thanks !

CodePudding user response:

For anyone in the future that has this problem, although you can't index on an NSArray, you can use the Xamarin method of :

GetItem<type>(index)

e.g

myArray.GetItem<NSObject>(0).

Works like a charm :)

  • Related