Put List of strings into NSUserDefaults object

2019-02-28 19:56发布

问题:

I've two ios application, first is contain app and second is today widget app.

In appdelegate class in contain app, I have List of symbols, which I want to pass with NSUserDefaults object, because I need to get this object in my today widget app.

My problem is that I cant store List of strings into NsUserDefaults object.

Object has several methods : SetBool, SetDouble, SetInt, SetString but there is no method which can take some object.

Only one method is which is taking NSObject for value and NSString for key.

Here is my code

  var userSharedContent = NSUserDefaults.StandardUserDefaults;
            var symbols = await DatabaseManager.Instance.GetRecentCoinsAsync(5); // returns list of tuples
            var listOfStrings = symbols.Select(o => o.symbol).ToList(); // take strings for tuples and conver it to List()

            userSharedContent.SetValueForUndefinedKey()

How can I solve this problem and Convert List into NSobject to pass it.

What is solution ? I've stacked in this task three days already. I want to pass data from one application to another application.

Please help me to solve this problem.

Thanks.

回答1:

NSUserDefaults works with "native" types, so you have to do some conversions between C# and ObjC types:

Write an NSArray of NSString from List<string>:

var listOfStrings = new List<string> { "One", "Two", "Three" };

using (var userDefaults = NSUserDefaults.StandardUserDefaults)
using (var nsArray = NSArray.FromStrings(listOfStrings.ToArray()))
{
    userDefaults.SetValueForKey(nsArray, new NSString("MyAppsValues"));
    userDefaults.Synchronize();
}

Read a List<string> from an NSArray of NSString:

List<string> listOfStrings = new List<string>();

using (var userDefaults = NSUserDefaults.StandardUserDefaults)
using (var nsArray = userDefaults.ValueForKey(new NSString("MyAppsValues")) as NSArray)
{
    for (uint i = 0; i < nsArray.Count; i++)
    {
        var cSharpStr = nsArray.GetItem<NSString>(i).ToString();
        listOfStrings.Add(cSharpStr);
    }
}