I'm trying to replicate Android's GenerateViewId() to assign a unique Tag to dynamically created UIViews in Xamarin.iOS.

internal static class LayoutExtensions
    // A tentative to mimmic Java's AtomicInteger used by GenerateViewId()
    // https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/View.java#27291
    private static int nextViewTag = 1;

    internal static int GenerateViewTag(this UIView someView)
            var result = nextViewTag;
            var newValue = result + 1;
            if (newValue > 0x00FFFFFF)
                newValue = 1; // Roll over to 1, not 0.
            if (nextViewTag == Interlocked.CompareExchange(ref nextViewTag, newValue, result))
                return newValue;

What do you think?

  • 1
    \$\begingroup\$ The result of the CAS compared to the current nextViewTag, instead of to result. Is that intentional, and what does that mean? \$\endgroup\$
    – harold
    Mar 31 '20 at 9:32
  • \$\begingroup\$ I'm not sure. The Android method returns a boolean that tells if the sNextGeneratedId.compareAndSet succeeded. \$\endgroup\$ Mar 31 '20 at 11:26
  • \$\begingroup\$ What is wrong with Interlocked.Increment(int)? \$\endgroup\$
    – user73941
    Apr 1 '20 at 17:08
  • \$\begingroup\$ @HenrikHansen I would like to be as close as possible as the original Java implementation. May be this is irrelevant. This is why I opened this question in the first place. \$\endgroup\$ Apr 2 '20 at 6:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.