DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Frameworks
  4. Swift: When removeFromSuperview() Is Not Enough

Swift: When removeFromSuperview() Is Not Enough

Here are some great tips for your Swift UI.

Simon Gladman user avatar by
Simon Gladman
·
Feb. 23, 15 · Tutorial
Like (0)
Save
Tweet
Share
17.75K Views

Join the DZone community and get the full member experience.

Join For Free



I've just added a little menu button with pop out UIAlertController to my Swift node based user interface demonstration. Along with options to change the selected node's type, it also allows the user to delete the current node.


At first glance, I thought this is simple: all I need to do is filter out the deleted node from presentation model's array of node value objects and invoke removeFromSuperview() on the widget itself. 

Aah, would that it were, would that it were.

There are a few issues that need to be resolved: simply removing the UI widget from its superview doesn't nullify it, so any observers it has on the presentation model are still active and, of course, it's still loitering around in memory wasting precious resources.
It takes a little additional work to be able to do this...

            nodeWidget.removeFromSuperview()
            nodeWidget = nil

...the first step being to make my NodeWidget class implement NilLiteralConvertible. Implementing this protocol means that my class has to have a convertFromNilLiteral() method that returns a nulled version of itself. My version looks like this: [See addendum below]

class func convertFromNilLiteral() -> Self
    {
        return self(frame: CGRectZero, node: NodeVO(name: "NULL_NODE", position: CGPointZero))
    }

Now, when I set an instance of NodeWidget to nil, it's properly deinitialised. As part of that process, its deinit is invoked and I can also remove any observers:

    deinit
    {
        NodesPM.removeObserver(self) // invokes notificationCentre.removeObserver(observer)

    }

I've also used UIView.animateWithDuration to make the deleted node fade out rather than suddenly vanish. This requires a temporary variable, nodeWidgetPendingDelete, that holds a reference to the deleted widget which is removed from its superview and nulled once the fade is completed:

UIView.animateWithDuration(NodeConstants.animationDuration, animations: {self.nodeWidgetPendingDelete!.alpha = 0}, completion: deleteAnimationComplete)

    [...]


    func deleteAnimationComplete(value: Bool)
    {
        if (value && nodeWidgetPendingDelete != nil)
        {
            nodeWidgetPendingDelete?.removeFromSuperview()
            nodeWidgetPendingDelete = nil
        }

    }

...and there we go: now the node isn't just removed from the view and hidden from the user, it's properly deinitialised and all its observers removed.
Of course, the related value object needs to be removed and any references to it in the inputs array of the other nodes need to be removed too. This is done in the presentation model using filters on the arrays:

static func deleteSelectedNode()
    {
        for node in nodes
        {
            node.inputNodes = node.inputNodes.filter({!($0 == NodesPM.selectedNode!)})
        }

        nodes = nodes.filter({!($0 == NodesPM.selectedNode!)})

        postNotification(.NodeDeleted, payload: selectedNode)
        postNotification(.RelationshipsChanged, payload: nil)

        selectedNode = nil

    }

My source code is now updated and available at my GitHub repository here.
Addendum Thanks to @ChromophoreApp for pointing out that the NilLiteralConvertable implementation is an unnecessary step. My first cut of the code accidentally had the reference to the deleted NodeWidget non-optional (i.e. no ?) which is why I couldn't set it to nil - a schoolboy error! Now that nodeWidgetPendingDelete is optional, I can set it to nil without jumping through hoops!

Swift (programming language)

Published at DZone with permission of Simon Gladman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Is a Kubernetes CI/CD Pipeline?
  • How to Create a Real-Time Scalable Streaming App Using Apache NiFi, Apache Pulsar, and Apache Flink SQL
  • Bye Bye, Regular Dev [Comic]
  • Differences Between Site Reliability Engineer vs. Software Engineer vs. Cloud Engineer vs. DevOps Engineer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: