<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yahya Saddiq on Medium]]></title>
        <description><![CDATA[Stories by Yahya Saddiq on Medium]]></description>
        <link>https://medium.com/@YSaddiq?source=rss-365ab7d62766------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JgZNjW3t8JdK6Rfc4eVrPg.jpeg</url>
            <title>Stories by Yahya Saddiq on Medium</title>
            <link>https://medium.com/@YSaddiq?source=rss-365ab7d62766------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:07:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@YSaddiq/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Power of Being the Smartest Person in the Room]]></title>
            <link>https://medium.com/@YSaddiq/the-power-of-being-the-smartest-person-in-the-room-4a18e4c6a4a4?source=rss-365ab7d62766------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a18e4c6a4a4</guid>
            <category><![CDATA[collaboration]]></category>
            <category><![CDATA[mentorship]]></category>
            <category><![CDATA[growth]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[professional-development]]></category>
            <dc:creator><![CDATA[Yahya Saddiq]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 03:54:46 GMT</pubDate>
            <atom:updated>2023-06-13T19:00:02.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGtWCePjHOYc7iIF0dExcQ.jpeg" /><figcaption>A man at the centre symbolizes the smartest person in the room exuding a growth mindset, surrounded by elements representing growth.</figcaption></figure><p>In the pursuit of personal and professional growth, we often seek out environments where we are challenged and inspired. However, it is essential to reflect on the Quranic verse 2:216: “<em>Perhaps you dislike something which is good for you and like something which is bad for you. Allah knows and you do not know.</em>” This verse reminds us that our perception of what is beneficial may not always align with Allah’s divine plan. When it comes to being the smartest person in the room, we may have reservations or doubts about its advantages. Yet, we must trust in Allah’s wisdom and recognize that He knows what is best for us, even when we do not fully comprehend it.</p><p>While seeking out individuals who push our boundaries is beneficial, it’s equally important to recognize the unique opportunities that come with being the intellectual frontrunner. In this article, we’ll explore why being the smartest person in the room doesn’t mean you’re in the wrong place for growth; in fact, it can be an advantageous position that fosters personal and professional development.</p><h3>The Gift of Mentorship</h3><p>Being the smartest person in the room opens doors to becoming a mentor and sharing your knowledge with others. Through teaching and guiding, you not only deepen your understanding but also enhance your communication and leadership skills. Mentoring others becomes a reciprocal process that propels both your growth and that of those around you.</p><h3>Confidence as a Catalyst</h3><p>Surrounded by individuals who challenge and inspire us, self-doubt can easily creep in. However, being the smartest person in the room brings a sense of confidence and self-assurance. This assurance empowers you to take on new challenges without fearing failure, ultimately propelling your growth in uncharted territories.</p><h3>Cultivating a Unique Perspective</h3><p>Being the intellectual frontrunner allows you to develop a distinctive perspective. Approaching problems and situations from different angles fosters creativity, innovation, and the ability to find fresh solutions. This unique outlook enables you to make breakthroughs and advancements that may not have been possible in a more challenging environment alone.</p><h3>The Power of Collaboration</h3><p>Although you may be the smartest person in the room, isolation is not the path to growth. On the contrary, it presents an incredible opportunity to seek collaboration with like-minded individuals or experts from different fields. Engaging with others and embracing diverse perspectives broadens your knowledge, expands your skill set, and accelerates your growth journey.</p><h3>Nurturing a Growth Mindset</h3><p>Growth and development are not solely dependent on the intelligence or skills of others but on our mindset and willingness to learn. Being the smartest person in the room does not signify the end of growth but an invitation to adopt a growth mindset. Set higher goals, pursue new areas of interest, and continuously challenge yourself intellectually, pushing the boundaries of your potential.</p><h3>Newbies &amp; Smartest</h3><p>Fresh graduates may question the benefits of being the smartest person in the room. However, this position offers numerous advantages for your growth and development:</p><ol><li>Your intelligence and expertise will impress employers, increasing your chances of securing desirable opportunities.</li><li>Your fresh ideas and problem-solving abilities make you a valuable asset to any team.</li><li>Being the smartest person allows you to lead your learning journey, enhancing skills and shaping your professional path.</li><li>Share your expertise through speaking engagements, writing, and thought leadership roles.</li><li>Embrace the chance to mentor others, strengthening leadership skills and deepening your understanding of your field.</li><li>Being the smartest person requires confidence, enabling you to tackle new challenges with resilience and adaptability.</li></ol><p>Embrace the advantages of being the smartest person in the room, and continue seeking opportunities for learning, collaboration, and self-improvement. It’s not about boasting, but utilizing your intelligence to drive growth and make a meaningful impact.</p><h3>Conclusion</h3><p>While seeking out those who challenge and inspire us is important, let us not discount the power of being the smartest person in the room. Embracing the opportunities for mentorship, building confidence, nurturing a unique perspective, seeking collaboration, and fostering a growth mindset can propel our personal and professional development to new heights. Let us celebrate growth in all forms and recognize the advantages of being the intellectual frontrunner.</p><p>So, my dear readers, let’s continue to learn, evolve, and embrace the opportunities that being the smartest person in the room presents. Together, we can create a community that thrives on collective growth.</p><p>What are your thoughts on this matter? I invite you to engage in the discussion and share your perspective in the comments below. Let’s celebrate growth together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a18e4c6a4a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating Suicide: Language Shift or Embracing Faith and Enhancing Mental Health Support]]></title>
            <link>https://medium.com/@YSaddiq/navigating-suicide-language-shift-or-embracing-faith-and-enhancing-mental-health-support-b55adff473f3?source=rss-365ab7d62766------2</link>
            <guid isPermaLink="false">https://medium.com/p/b55adff473f3</guid>
            <category><![CDATA[mental-health]]></category>
            <category><![CDATA[islam]]></category>
            <category><![CDATA[suicide]]></category>
            <category><![CDATA[raising-awareness]]></category>
            <category><![CDATA[faith]]></category>
            <dc:creator><![CDATA[Yahya Saddiq]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 05:27:25 GMT</pubDate>
            <atom:updated>2023-06-09T05:27:25.363Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4QFR-SYoghxRCzoU4sx3Q.jpeg" /><figcaption>A person standing at the intersection of a mosque and a mental health symbol</figcaption></figure><p>As a practising Muslim, I am not a doctor or religious leader. However, I feel a responsibility to discuss the recent movement advocating for a change in the language surrounding suicide. In this article, I aim to shed light on the Islamic perspective on this matter.</p><p>Suicide is a sensitive and complex topic that deserves thoughtful consideration from various perspectives. In Islamic belief, suicide is viewed as a grave sin and a deliberate choice. While some advocate for changes in the language surrounding suicide, highlighting that individuals do not “commit” suicide but rather die by suicide due to the immense difficulties they encounter, it is essential to understand the Islamic religious standpoint and work towards improving mental health support systems within this framework.</p><h4>The Islamic View on Suicide</h4><p>Islamic teachings emphasize the sanctity of life and explicitly prohibit self-harm and suicide. In verse (4:29), the Quran instructs believers, “<em>And do not kill yourselves. Surely Allah is ever Merciful to you</em>.” This verse serves as a clear reminder that taking one’s own life is contrary to the will of the Creator and is considered a transgression.</p><h4>Respecting Religious Teachings</h4><p>While it is crucial to approach mental health issues with empathy and compassion, it is equally important to acknowledge and respect religious beliefs that guide our understanding of certain actions. In the case of suicide, Islamic teachings unequivocally consider it a violation of the trust that Allah has bestowed upon individuals to preserve and protect their lives.</p><h4>Comprehensive Approach and Mental Health Support</h4><p>Rather than solely focusing on changing language, adopting a comprehensive approach that aligns with Islamic principles and improves mental health support systems is essential. This approach includes raising awareness, providing education, and establishing resources that address mental health challenges while adhering to religious teachings.</p><h4>Raising Awareness and Education</h4><p>Educating individuals about mental health, including the complex factors that contribute to suicide, can help reduce stigma and promote understanding. This includes recognizing the signs of distress, encouraging open conversations, and emphasizing the importance of seeking professional help when needed. Religious leaders and scholars can play a significant role in promoting mental health education within the Islamic community.</p><h4>Support Systems within Islamic Framework</h4><p>Creating supportive environments within the Islamic community involves establishing mental health services that consider religious sensitivities. Mosques, community centres, and Islamic organizations can offer counselling services, support groups, and referrals to mental health professionals who understand the intersection of faith and mental well-being. Collaboration between mental health experts and religious leaders can help bridge the gap between religious teachings and mental health support.</p><h4>Embracing Faith and Compassion</h4><p>Striving for a comprehensive approach that combines improved mental health services and adherence to Islamic teachings demonstrates a commitment to both faith and compassion. By recognizing the gravity of suicide from an Islamic standpoint and working towards providing support within the boundaries of religious teachings, we can address the underlying issues while respecting the values and beliefs that guide us in our faith.</p><h4>Conclusion</h4><p>Understanding suicide from an Islamic religious perspective reveals the prohibition and gravity of the act within the faith. While some advocate for changes in language, it is essential to recognize and respect the religious teachings that guide our understanding. By embracing faith and improving mental health support systems within an Islamic framework, we can foster an environment of empathy, awareness, and compassion that addresses mental health challenges while respecting our religious principles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b55adff473f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Purifying the Heart: Overcoming Ego for Personal & Spiritual Growth]]></title>
            <link>https://medium.com/@YSaddiq/purifying-the-heart-overcoming-ego-for-personal-spiritual-growth-b52a7cff75c?source=rss-365ab7d62766------2</link>
            <guid isPermaLink="false">https://medium.com/p/b52a7cff75c</guid>
            <category><![CDATA[self-awareness]]></category>
            <category><![CDATA[spiritual-growth]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[purifying-the-heart]]></category>
            <category><![CDATA[overcoming-the-ego]]></category>
            <dc:creator><![CDATA[Yahya Saddiq]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 11:29:25 GMT</pubDate>
            <atom:updated>2023-06-04T14:57:33.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A person gazing in the sightline, seeking clarity." src="https://cdn-images-1.medium.com/max/1024/1*NQbrpgmQd6pwFqewK4PZTA.jpeg" /><figcaption>A person gazing in the sightline, seeking clarity.</figcaption></figure><p>In our quest for spiritual growth and personal development, two remarkable books, <a href="https://www.goodreads.com/en/book/show/272724">“<strong><em>Purification of the Heart</em></strong>” by Hamza Yusuf</a> and <a href="https://www.goodreads.com/book/show/27036528-ego-is-the-enemy">“<strong><em>Ego is the Enemy</em></strong>” by Ryan Holiday</a> offer profound insights into the path of self-discovery and inner transformation.</p><p>Although these books may appear distinct, their interconnectedness reveals a powerful synergy that can guide us toward a profound shift in our lives. By embracing the teachings within these books, we can gain awareness and guidance to overcome ego-driven challenges, foster inner purification, and embark on a transformative journey of spiritual evolution.</p><h4>Recognizing the Destructive Ego</h4><p>“<em>Ego is the Enemy</em>” illuminates the detrimental impact of the ego on our lives, hindering progress and blinding us to our own limitations. By understanding that the ego is a formidable barrier, we can cultivate a mindset of humility and self-awareness that enables us to transcend its influence.</p><h4>Spiritual Diseases and the Heart</h4><p>“<em>Purification of the Heart</em>” delves into the spiritual diseases that afflict our hearts and souls. These diseases, such as envy, arrogance, and anger, are intimately connected to the ego’s dominance. By recognizing the signs and symptoms of these diseases within ourselves, we become equipped to embark on the journey of healing and purification.</p><h4>Illuminating the Destructive Influence of the Ego</h4><p>Drawing parallels to “<em>Ego is the Enemy</em>” we find a common thread. Both books shed light on the destructive influence of the ego — whether from a spiritual or secular perspective. The ego, with its self-centeredness and arrogance, poses a significant obstacle to personal development, success, and harmonious relationships. Recognizing this connection, we can approach our personal and spiritual growth with renewed clarity. By cultivating self-awareness, practicing self-discipline, and humbling ourselves before Allah(God), we can embark on a transformative journey of purifying our hearts and taming our egos.</p><h4>Embracing Self-Reflection</h4><p>Both books emphasize the vital role of self-reflection. By engaging in introspection and honestly examining our thoughts, behaviors, and intentions, we gain clarity and insight into the destructive patterns of the ego. This self-awareness becomes the catalyst for personal growth and spiritual elevation.</p><h4>Embracing Humility</h4><p>Humility is a powerful antidote to the ego’s grip. By acknowledging our inherent human limitations and surrendering the need for excessive self-importance, we open ourselves to true growth and connection. The <strong>Prophet Muhammad (PBUH) </strong>said, “<em>He who humbles himself for the sake of Allah, Allah will elevate him.</em>” Embracing humility allows us to tap into our authentic selves and find solace in the Divine.</p><h4>Seeking Guidance</h4><p>Islam emphasizes the purification of the heart (Tazkiyah) as a means to attain spiritual well-being. “<em>Successful indeed is the one who purifies their soul. and doomed is the one who corrupts it</em>” Qur’an 91:9–10. These verses underscore the importance of purifying the heart for both spiritual and life success.</p><h4><strong>Practicing Self-Discipline</strong></h4><p>Conquering the ego requires self-discipline and restraint. “<em>˹They are˺ those who, upon committing an evil deed or wronging themselves, remember Allah and seek forgiveness and do not knowingly persist in sin — and who forgives sins except Allah?</em>” Qur’an verse 3:135. This verse encourages self-discipline and seeking forgiveness as a means to overcome ego-driven actions.</p><h4>Fostering Transformational Practices</h4><p>The Qur’an and sayings of the Prophet Muhammad (PBUH) provide a wealth of wisdom and guidance for our spiritual journey. By immersing ourselves in these sacred texts and reflecting upon their teachings, we gain profound insights that aid in combating the ego and nurturing the heart.</p><p>Both books offer practical guidance on cultivating positive habits and practices that counteract the ego’s influence. Engaging in acts of worship, such as prayer, fasting, and charity, serves as a means to discipline the ego, instill selflessness, and nurture a deeper connection with the Divine.</p><h3>Personal Experience: A Profound Awakening</h3><p>In addition to the timeless teachings found in “<em>Purification of the Heart</em>” and “<em>Ego is the Enemy</em>” my personal journey has provided me with profound insights into the significance of overcoming the ego and purifying the heart. Allow me to share a transformative experience that forever changed my perspective.</p><p>In the depths of a life-altering car accident that left me unconscious for 14 days, I emerged with a profound awakening. As I opened my eyes to a world of uncertainty and confusion, the fragility of life and the immense mercy of Allah(God) became undeniably clear. The accident served as a catalyst, propelling me into a transformative journey of self-discovery, spiritual growth, and gratitude.</p><p>Through the teachings of Islam, the wisdom imparted in “<em>Purification of the Heart</em>” and the lessons learned from “<em>Ego is the Enemy</em>” I have embraced self-reflection, humility, and a profound connection with the Divine. This awakening has forever changed me, instilling empathy, unity, and a deep appreciation for the beauty of every moment Allah grants us.</p><h3>Conclusion</h3><p>The convergence of “<em>Purification of the Heart</em>” and “<em>Ego is the Enemy</em>” creates a powerful alliance in our pursuit of spiritual growth and personal development. By recognizing the destructive nature of the ego and embarking on a journey of inner purification, we can transcend its limitations and align ourselves with higher virtues.</p><p>Embracing self-reflection, humility, and the wisdom contained within Qur’an Prophet Muhammad&#39;s (PBUH) sayings, we open ourselves to profound transformation. Let us embrace this unified path, empowering ourselves to overcome ego-driven challenges, elevate our spiritual consciousness, and embark on a life of purpose, authenticity, and connection.</p><p>Remember, within the depths of self-discovery lies the key to unlocking our true potential and experiencing the beauty of a purified heart.</p><h3>Resources</h3><ol><li><a href="https://www.goodreads.com/en/book/show/272724">“Purification of the Heart” by Hamza Yusuf</a></li><li><a href="https://www.goodreads.com/book/show/27036528-ego-is-the-enemy">“Ego is the Enemy” by Ryan Holiday</a></li><li><a href="https://quran.com/">The Holy Qur’an</a></li><li><a href="https://sunnah.com/">The Prophet Mohamed&#39;s sayings</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b52a7cff75c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should I learn Flutter?]]></title>
            <link>https://blog.devgenius.io/should-i-learn-flutter-5dd91ab06a4f?source=rss-365ab7d62766------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dd91ab06a4f</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[cross-platform]]></category>
            <dc:creator><![CDATA[Yahya Saddiq]]></dc:creator>
            <pubDate>Sat, 10 Jul 2021 09:45:20 GMT</pubDate>
            <atom:updated>2021-07-10T10:18:43.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipFXkH2w0ptGaIoRvWum0w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@benjaminsweet?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ben Sweet</a> on <a href="https://unsplash.com/s/photos/human?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>What is Flutter?</h3><p>Flutter is Google’s UI framework(not a language) to build apps for android, iOS, progressive web apps, and desktop from a single codebase.</p><p>Flutter improves upon most cross-platform tools due to a super-fast rendering engine that makes your Flutter apps perform nearly, or even exactly, the same as native apps. First-class support for reactive programming, cross-platform abstractions, and its virtual machine allows for hot reloading of code changes.</p><p>Using <strong><em>hot-reload</em></strong>, you’d rarely need to rebuild your apps as you develop them. A running app in a simulator or emulator will refresh with code changes automatically as you save your source files!</p><p>Flutter supports all the great language features software developers have come to like and expect, such as <strong>async/await</strong> for concurrency management<strong>, type inference </strong>for clean, type-safe code and <strong>null safety.</strong></p><p>Flutter comes with great animations and transitions, you can be creative and flexible with the UI.</p><p>And many more!</p><h3>What Should I Learn, Flutter or SwiftUI?</h3><p>Both, it is beneficial to know both of them. So that when the times come, you can be the most productive.</p><p>The only barrier is that you have to excel in both Swift and Dart programming languages. As these two languages are strongly typed languages and Flutter and SwiftUI are declarative based, so it isn’t a big deal.</p><p>If you know Kotlin, Swift, Java, or Typescript, you’ll find Dart familiar, since it’s an object-oriented C-style language.</p><h3>When Should I use Flutter?</h3><p>Flutter supports many, but not all, native features. It also produces app binaries that are bigger in size than those built with platform frameworks.</p><p>if you’re working with a highly-customized iOS app based on CloudKit that uses all the native hardware, MLKit and StoreKit. Maintaining and taking advantage of those features will be easier using SwiftUI.</p><p>Flutter doesn’t support Apple Bitcode yet, watchOS, tvOS, or certain iOS app extensions. But they’re working on it.</p><h3>Finally!</h3><p>For years, we have been promised to write once and run anywhere; Flutter may well be the best attempt yet at achieving that goal. It allows you to build a high-quality app that’s performant and looks great, very quickly.</p><p>Keep in mind, that we humans always have a great capacity to consume a variety of knowledge and create awesome things.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dd91ab06a4f" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/should-i-learn-flutter-5dd91ab06a4f">Should I learn Flutter?</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Management Part 2: Reference Cycles, Closures and Debugging]]></title>
            <link>https://blog.devgenius.io/memory-management-part-2-reference-cycles-closures-and-debugging-59b917dc064b?source=rss-365ab7d62766------2</link>
            <guid isPermaLink="false">https://medium.com/p/59b917dc064b</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Yahya Saddiq]]></dc:creator>
            <pubDate>Sun, 27 Jun 2021 08:54:18 GMT</pubDate>
            <atom:updated>2021-07-05T16:22:26.640Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article is based on my talks at <a href="https://www.youtube.com/watch?v=GvaMzX8mwRI">CocoaHeads Berlin</a> and <a href="https://nslondon.com/#yahya-saddiq-swift-memory-management-and-debugging">NSLondon</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*th7UcepA1hcPWlaYKJnjxQ.jpeg" /><figcaption>My son “Yusuf” once told me that elephants are capable to remember water sources for decades. Photo by <a href="https://unsplash.com/@photosbybeks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Photos By Beks</a> on <a href="https://unsplash.com/s/photos/elephant?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.</figcaption></figure><p>Welcome to the second part of this mini-series on Memory Management! This part carries on from <a href="https://blog.devgenius.io/memory-management-part-1-regions-types-and-leaks-884c231f5135">Part 1: Regions, Structures and Leaks</a>. I recommend you start with the first part of this article series to get the most out of it.</p><p>In this article, you’ll learn about:</p><ul><li>Breaking reference cycle in classes and closures</li><li>Escaping &amp; non-escaping closures</li><li>Delayed deallocation</li><li>Xcode memory debugger</li><li>Locating the leak 🕵🏽‍♂️</li></ul><h3>Follow up!</h3><p>In the previous part; the book, author and editor were stuck in the heap memory region and their memory slots weren’t reusable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCmYS7VOWgXJBZlUZ8Y3Gg.png" /></figure><p>Because book and author have a reference to each other and each instance keeps the other one alive, same as for book and editor.</p><p>And we made things worse by ending the scope, the stack list items will be deallocated and there are no more references to the initial objects.</p><p>This is a classic case of a reference cycle, which leads to a software bug known as a <strong>memory leak</strong>. With a memory leak, memory isn’t freed up even though its practical lifecycle has ended.</p><h3>Breaking Reference Cycle</h3><p>So, can you guess which class should we 🛠👷🏽‍♂️👷🏽‍♀️?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZnEM7uAmf30E8Dv9mwewA.png" /></figure><p>Exactly, the <strong>book</strong> class, because it’s not the owner class and it stores references to its owners in properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEeBXyqpVqW-VyiDViF7Ew.png" /></figure><p>A <strong>book</strong> isn’t always assigned to an <strong>editor</strong>, so let’s model it as an <strong>optional</strong> type. And the <strong>book</strong> doesn’t own the <strong>editor</strong>, so it makes sense to make it a <strong>weak reference </strong>as well.</p><p><strong>Weak means</strong> the reference in this variable will not take part in reference counting. When a reference isn’t weak, it’s called a <strong>strong reference</strong>, which is the default in Swift.</p><p>The great thing about using <strong>weak</strong> variables is that they automatically detect when the underlying object has gone away. This is why they are <em>always </em>declared with an optional type and a var. Because they become nil once the reference count reaches zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWCBsukGya9hOP_lmcUUfQ.png" /></figure><p><strong>Unowned references </strong>is<strong> </strong>another way to break reference cycles, which behave much like <strong>weak</strong> in that they don’t change the object’s reference count. But Unlike weak references, they <strong>always </strong>expect to have a value — you can’t declare them as optional.</p><p>Think of it this way: A <strong>book</strong> cannot exist without an <strong>author</strong>. At the same time, a book does not “own” the author therefore the reference should be <strong>unowned</strong>.</p><p>Here we guarantee that a book always has an author, hence, the author is not declared as optional. And a book can have an editor at a certain time, hence, the editor is declared optional.</p><p>On the other hand, books is a variable, so it can be modified after initialization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldy0BZqDh5TeJaULco852w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_BvSingr3vfhI1oft0XCQ.png" /></figure><p>Voila! our code breaks the reference cycle with the <strong>weak</strong> and <strong>unowned</strong> keywords.</p><p>All the deinit methods run and they will be de-allocated.</p><h3>Closures</h3><p>Closure is simply a function with no name; you can assign it to a variable and can be passed around like any other value.</p><p>They are named “Closures” because they can “close over” the variables and constants within the closure’s scope.</p><p>This simply means that closure can access, store and manipulate the value of any variable or constant from the surrounding context.</p><p>The variables and constants used within the body of closure are said to have been <strong>captured </strong>by the closure.</p><p>There are two types of closure, non-escaping and escaping.</p><h4>Non-escaping Closure</h4><p>In Swift, closures are non-escaping by default and they are:</p><ul><li>Non-storable.</li><li>Executed in scope.</li><li>Doesn’t cause a reference cycle.</li></ul><p>No need to use [weak or unowned self] for non-escaping closure, if you don’t mind delayed deallocation.</p><h4>Escaping closure</h4><ul><li>Storable</li><li>Can be passed to other closures.</li><li>Can be executed in the future.</li><li>Causes<strong> reference cycles.</strong></li></ul><p>🤔 How escaping closure could cause a reference cycle?</p><p>Swift is a safe language, closures extend the lifetime of any object they use to guarantee those objects are alive and valid.</p><p>This automatic safety is cool, but it’s the reason for the reference cycle if you extend the lifetime of an object that itself captures the closure.</p><p>let’s see that in an example!</p><h3>Reference Cycle in Escaping Closures</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yHWvCpftnJUiJJsu70WTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VvwS-LEPu-mPo10sJyIKA.png" /></figure><p>For example, if you add a lazy property that computes the book’s description for the book class.</p><p><strong>Note:</strong> a <strong>lazy property </strong>isn’t assigned until its first use and that self is only available after initialization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0sIDWBSusiCYl_iXbvRPZA.png" /></figure><p>When we call the <em>book.description()</em> in our scope, the book object creates a block of memory for the <em>description()</em> and holds its reference. At the same time <em>description()</em> strongly captures self through title and author which in turn increases the reference count for the book object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XbUjaMXea1hWlt-jgd9uqQ.png" /></figure><p>Again we have a reference cycle, now between the book and the <em>description()</em>. At end of the scope, only the author’s deinit method will be called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6eci64QQuuNR4ti9Oo9F5Q.png" /></figure><h3>Breaking Closure Reference Cycle</h3><p>To break the cycle, you’ll need to know about a language feature called <strong>capture list</strong>.</p><p><strong>Capture list is </strong>a language feature to help you control exactly how a closure extends the lifetime of objects it refers to. They are a list of variables captured by a closure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*tFigzjf2T3UGMvX20-nWMQ.png" /></figure><p>Since the closure shouldn’t exist after you release the book object from memory, self will never be nil, so we can change the strong reference to an <strong>unowned</strong> one using a capture list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7CoE9Um_4-vGYvuvd2Jig.png" /></figure><p>No more reference cycle, Swift will deallocate description object by the end of the scope.</p><h4>[weak self]</h4><p>There are certain times when you can’t capture self as an unowned reference, because self might become nil and the app will crash for reading a nil object.</p><p><strong><em>[weak self]</em></strong> means that the closure will not extend the lifetime of self, but If the underlying object representing self goes away, it gets set to nil.</p><p>The app won’t crash if self goes away but does generate a “String interpolation” warning which you can fix by the <strong>strong-weak pattern.</strong></p><p><strong>Note:</strong> It’s wise and always recommended to use <em>[weak self]</em> instead of unowned.</p><h3>When should I use [weak self]?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxmOjobeJkPQhkWVaS66ug.png" /><figcaption><a href="https://medium.com/flawless-app-stories/you-dont-always-need-weak-self-a778bec505ef">You don’t always need a weak self</a>, Besher Al Maleh</figcaption></figure><p>Here’s a comprehensive flow chart by <a href="https://medium.com/flawless-app-stories/you-dont-always-need-weak-self-a778bec505ef"><strong>Besher Al Maleh</strong></a> to decide whether your closure is escaping and need <strong><em>[weak self]</em></strong> or not.</p><h3>Reference Cycle — GCD</h3><p>GCD doesn’t cause a reference cycle unless you store it for future execution.</p><h3>Reference Cycle — Animation</h3><p><em>UIView.animate()</em> doesn’t cause a reference cycle unless you store a <em>UIViewPropertyAnimator</em> for future execution.</p><h3>Reference Cycle — Timer</h3><p>A timer is different. It can retain an object even if it’s not stored in a property.</p><p>As long as the timer repeats and self isn’t captured in it, the timer will prevent the referenced object from deallocating due to indefinitely delayed deallocation rather than a memory leak.</p><p>Keep in mind to invalidate when a timer is not needed and weakly capture self in it.</p><h3>Delayed Deallocation</h3><p>This is not a memory leak, it’s a side effect that happens in both escaping and non-escaping closures. This side effect leads to undesired behaviours.</p><p>As we said earlier, if you didn’t weakly capture self<em>,</em> closures capture strongly any variable or constant from the surrounding context. This means closures will prevent strongly captured objects from getting deallocated for as long as the closure body is alive.</p><p><a href="https://medium.com/flawless-app-stories/you-dont-always-need-weak-self-a778bec505ef">Check this article</a> to learn about the scenarios that can keep the closure body is alive.</p><h3>BookShop</h3><p>Finally, time to show reference cycles using the Xcode Memory Debugger. I’m going to use a demo app BookShop (download the Bookshop app from <a href="https://github.com/ysadiq/BookShop/tree/develop/Final"><strong>here</strong></a>) to show you memory visualization and leak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IMz-v5Ew4AjhoD9faDJZCg.png" /></figure><p>The demo app is a simple two views and a table app. It contains a book data stub with the publishing house model I talked about in <a href="https://blog.devgenius.io/memory-management-part-1-regions-types-and-leaks-884c231f5135">Part 1: Regions, Structures and Leaks</a>.</p><h3>Xcode Memory Debugger</h3><p>Apple introduced the new visual memory debugger in Xcode 8. Run the Bookshop app and debug the memory graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3B_5RZ3CIU-5Y59jjfnt-A.gif" /></figure><p>The memory debugger breaks the execution of the app and builds a visualization of memory usage at the current time and makes it easier to locate, diagnose and fix memory leaks. Note that graph drawing might take a little while, depending on how big your app is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tc56GtnZfxSGiK0k5rpNAA.png" /></figure><p>The navigator window on the left shows the objects created on the heap organized by type and instance.</p><p>When you select an object in the navigator, the middle section will show you the memory graph of the selected object, and the relationships it has to other objects. The type of relationship is denoted by the style of the arrow. If the arrow is bold that’s a strong relation otherwise it’s a conservative relationship (🤔 Swift doesn’t recognize it, it could be weak or strong).</p><p>Sometimes, it’s a big graph, other times, it’s a smaller graph with just a couple of objects. The memory inspector on the right side shows details such as the size, class hierarchy and allocation backtrace.</p><p>Awesome! Memory doesn’t show any leaks so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5i8UhdlI4z8qiJWH6qB2Lg.gif" /></figure><p>Now, unpause the app and release the current view and objects by going back to the root view. Then open the memory graph again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sp2MdB9JfE_vIMiVRYS8Kw.png" /></figure><p>Oops! The book neither author objects have been released. This happens because the book is strongly holding the author and the author is strongly holding the book in an array list. That’s a reference cycle that caused memory leaks. The more bookshop view you open, the more leaks the memory will have.</p><p>As I have mentioned earlier, a memory leak is a memory that was allocated at some point but was never released and is no longer referenced by your app. Since there are no references to it, there’s no way to release it and that memory location cannot be used again.</p><h3>Locating the Leaking Source 🕵🏽‍♂️</h3><p>Debugging memory-related bugs can be time-consuming if you do not know where to start looking. Fortunately, Xcode includes options for identifying memory problems closer to when those problems happen.</p><p>Apple has Malloc library which provides debugging features to help tracking down:</p><ul><li>Memory smashing bugs</li><li>Heap corruption</li><li>References to freed memory</li><li>Buffer overruns.</li></ul><p>This feature is not enabled by default, you can enable these debugging options through a set of environment variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eS04rCr1QixricWMHLvOpg.gif" /></figure><p>There’s a lot of Malloc environment variables, the one I care about now is <strong>Malloc Stack Logging, </strong>it<strong> </strong>allows<strong> </strong>malloc to remember the function call stack at the time of each allocation.</p><p>This is something that is enabled per scheme. When you are not debugging memory leaks you should turn off malloc stack logging. Because of its intensive recording process and some properties aren’t logged fully when stepping through with the debugger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*agi_SvTx1M6fHOM8rrKvEA.png" /></figure><p>If you enabled malloc stack logging, the backtrace will show you the allocation line in your code for each object in the memory graph. Usually, the allocation lines are harmless and the problem is before or after that line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jf6ZzWmkL-rkeFJtdLArZQ.gif" /></figure><p>As we mentioned in the diagram at the beginning of this article, to fix this memory leak you have to change the book-author relationship into an <strong>unowned</strong> one. A <strong>book</strong> cannot exist without an <strong>author,</strong> at the same time, a book does not “own” the author.</p><h3>Where to Go From Here?</h3><p>3 final tips to help you eliminate memory bugs:</p><ol><li>Have a strong code style defined for your project and respect it.</li><li>Use <a href="https://github.com/realm/SwiftLint">Swift Lint</a>. It is a great tool to detect early issues at compile-time.</li><li>Profile the app frequently especially before creating a feature or a fix pull-request using Xcode Memory Debugger.</li></ol><p>Awesome! you’ve reached the end of this mini-series.</p><p>In this article, you’ve learned how to break reference cycles in both classes and closures, Xcode memory debugger and how to locate leaks using Apple’s Malloc library.</p><h4>References</h4><p><strong>Books<br>- </strong><a href="https://www.raywenderlich.com/books/swift-apprentice">Swift Apprentice</a>, Raywenderlich</p><p><strong>Articles<br>- </strong><a href="https://swiftrocks.com/memory-management-and-performance-of-value-types.html">Memory management and performance of value types</a>, Swift Rocks<br><strong>-</strong> <a href="https://deepu.tech/memory-management-in-programming/">Memory management in programming</a>, Deepu Tech<br><strong>-</strong> <a href="https://gribblelab.org/CBootCamp/7_Memory_Stack_vs_Heap.html">Memory Stack vs Heap</a>, Gribble lab<br><strong>-</strong> <a href="https://medium.com/young-coder/an-illustrated-guide-to-memory-the-stack-the-heap-and-pointers-40a604f7bc53">An illustrated guide to memory, stack, heap and pointer</a>, Young Coder<br><strong>-</strong> <a href="https://useyourloaf.com/blog/xcode-visual-memory-debugger/">Xcode visual memory debugger</a>, Use Your Loaf<br><strong>-</strong> <a href="https://doordash.engineering/2019/05/22/ios-memory-leaks-and-retain-cycle-detection-using-xcodes-memory-graph-debugger/">Memory leaks and retain cycle detection</a>, DoorDash Engineering<br><strong>- </strong><a href="https://medium.com/flawless-app-stories/you-dont-always-need-weak-self-a778bec505ef">You don’t always need a weak self</a>, Besher Al Maleh</p><p>I hope you enjoyed this article. If you have any question or comment, don’t hesitate, just drop them down here 🤗.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59b917dc064b" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/memory-management-part-2-reference-cycles-closures-and-debugging-59b917dc064b">Memory Management Part 2: Reference Cycles, Closures and Debugging</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Management Part 1: Regions, Types and Leaks]]></title>
            <link>https://blog.devgenius.io/memory-management-part-1-regions-types-and-leaks-884c231f5135?source=rss-365ab7d62766------2</link>
            <guid isPermaLink="false">https://medium.com/p/884c231f5135</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[retain-cycle]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Yahya Saddiq]]></dc:creator>
            <pubDate>Fri, 25 Jun 2021 15:57:30 GMT</pubDate>
            <atom:updated>2021-07-05T16:21:43.935Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article is based on my talks at <a href="https://www.youtube.com/watch?v=GvaMzX8mwRI">CocoaHeads Berlin</a> and <a href="https://nslondon.com/#yahya-saddiq-swift-memory-management-and-debugging">NSLondon</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*th7UcepA1hcPWlaYKJnjxQ.jpeg" /><figcaption>My son “Yusuf” once told me that elephants are capable to remember water sources for decades. Photo by <a href="https://unsplash.com/@photosbybeks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Photos By Beks</a> on <a href="https://unsplash.com/s/photos/elephant?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.</figcaption></figure><p>You, as a mobile software engineer should be conscious of your apps’ memory footprint. It’s recommended to check your app memory usage before delivering a fix or new feature for your app or framework.</p><p>You should be conscious to avoid retain cycles and memory leaks which are major memory-related issues that cause unwanted side effects, bad user experience and crashes.</p><p>This article will give you some insights into what’s happening under the hood of Swift language in terms of memory management and how to debug memory issues specifically leaks and retain cycles.</p><p>In this article, you’ll learn about:</p><ul><li>Memory and why its management is important</li><li>Differences between stack and heap memory regions</li><li>Class and struct lifecycle</li><li>Reference counting</li><li>Automatic reference counting vs garbage collection</li><li>Reference cycle</li><li>Memory leak</li></ul><h3><strong>Why Memory Management is Important?</strong></h3><p><strong>Softwares need memory access to:</strong><br>1. Load software’s bytecode<br>2. Store both software’s data values and structures<br>3. Load any software’s required run-time systems</p><p>Unlike Hard disk drives, RAM is not infinite. If a program keeps on consuming memory without freeing it, ultimately it will run out of memory and crash itself or even worse crash the operating system.</p><p>Therefore, instead of letting the software developer figure this out, most programming languages provide ways to do automatic memory management.</p><h3><strong>Stack vs Heap</strong></h3><p>Any software program uses 2 memory regions known as Stack and Heap. Both stack and heap have essential roles in the execution of any program.</p><p>A general understanding of what they are and how they work will help you visualize the functional differences between a class and a struct(in other words, reference semantics and value semantics) and how you should utilize memory usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*-oTwbOMIYEYkGaBWQSMlKw.png" /><figcaption>The Stack</figcaption></figure><p><strong>Stack</strong> is organized and managed by the CPU. It’s used for <strong>static memory allocation</strong> and as the name suggests it is a last in first out stack (Think of it as a stack of pancakes 🥞).</p><p>Due to this nature, the process of storing and retrieving data from the stack is <strong>very fast</strong> as there is no lookup required, you just store and retrieve data from the topmost block on it.</p><p>Multi-threaded applications usually have a stack per thread.</p><p><strong>Local variables</strong>(value types, primitive constants) and <strong>pointers</strong> are the typical data that the system stores on the stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*xfk0p1CK4ko82noo8HQ_lg.png" /><figcaption>The Heap</figcaption></figure><p>On the other hand, the heap doesn’t organize data. It just leaves everything scattered around (like a heap of red bricks 🧱).</p><p>The heap is a large pool of memory from which the system can request and dynamically allocate blocks of memory. The system uses the <strong>heap </strong>to store instances of reference types such as <strong>Class</strong>, <strong>Closures</strong> and now <strong>Actors</strong> with Swift 5.5.</p><p>The heap doesn’t automatically destroy its data as the stack does; a programming language requires additional work to do that. This makes creating and removing data on the heap a slower process, compared to on the stack.</p><p>When we talk about memory management we are mostly talking about managing the Heap memory.</p><p>Memory, as everybody else has a good relationship with the 🥞.</p><h3>Class vs Struct</h3><p>In Swift, class is a reference type. A variable of a class type doesn’t store an actual instance — it stores a <strong>reference </strong>to a location in memory that stores the instance using <strong><em>assign-by-reference</em></strong>.</p><p>While a struct is a value type that stores the actual value using <strong><em>assign-by-copy</em></strong> and provides direct access to it.</p><p>Let’s break this down using an author class and a person struct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*jj86OYuLnXoL6xBkk21PZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XS1qfYquRzeq1sn8wqOeQ.png" /></figure><ol><li>A <strong>person</strong> instance would not reference a place in memory but the value would instead belong to person exclusively.</li><li>A new <strong>father</strong> instance for the same <strong>person</strong> will be <strong>assigned-by-copy</strong> and take a new place in the stack.</li><li>An instance of <strong>author</strong> class will create an object in the heap and store its address in the stack.</li><li>A new constant <strong>awesomeAuthor</strong> for the same auhor instance will be <strong>assigned-by-reference</strong> by holding the same address and point to the same place in memory.</li></ol><p><strong>Note:</strong> value types are not necessary value semantics, that’s another topic for another article. But it’s important to keep that in mind 🤔.</p><h3>Reference Counting</h3><p>So far, we know that reference type objects are stored on the heap. Objects on the heap are <em>not </em>automatically destroyed, because the heap has a dynamic nature and is trickier to manage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*KnMR2vBxoiLJJ5O8vT8X_A.png" /></figure><p>Without the utility of the call stack, there’s no automatic way for a process to know that a piece of memory will no longer be in use.</p><p>In Swift, the mechanism for deciding when to clean up not-used objects on the heap is known as <strong>reference counting</strong>.</p><p>In short, <strong>reference counting </strong>gives<strong> </strong>each object a reference count that’s incremented for each constant or variable with a reference to that object and decremented each time a reference is removed.</p><p>When a reference count reaches zero, the object is abandoned since nothing in the system holds a reference to it. When that happens, Swift will clean up the object and marks that memory as free.</p><p>Let’s demonstrate this using the same author class we used above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBMOXUS_vL3D0V5Uvh8DFA.png" /></figure><p>Creating an instance of <strong>author</strong> creates an object in the heap with a reference count of 1 and keep its address in the stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TAC5xoJZO1VPdiciN3uRBw.png" /></figure><p>Creating <strong>anotherAuthor</strong> for the same <strong>author</strong> instance increments its reference count to 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwEr3rg6Bd0PNOQdGFl2YQ.png" /></figure><p>Creating <strong>lotsOfAuthor</strong> array of same <strong>author </strong>and<strong> anotherAuthor </strong>instances increments it to 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSJkNI-MoN0OYPisi6u3ZA.png" /></figure><p>Discarding <strong>anotherAuthor</strong> decrements author’s reference count to 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXngdhAl2gKPiqWT6Ym7vg.png" /></figure><p>Discarding <strong>lotsOfAuthor</strong> elements, decrement it to 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjjCNDo72VM7nXrNPi7KTg.png" /></figure><p>Now! Assigning a new <strong>author</strong> object to the original author variable:</p><ol><li>Decrements the original author object to zero</li><li>Mark the old abandoned object’s memory block as free</li><li>Creates a new author object with reference count = 1</li></ol><p>In the above example, you don’t have to do any work to increase or decrease the object’s reference count. That’s because Swift has a feature known as <strong>automatic reference counting </strong>or <strong>ARC</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9M9uRDulliBxwfqFpXnBMw.png" /></figure><p>While some older languages require you to increment and decrement reference counts in your<em> </em>code manually, the Swift compiler adds these calls automatically at compile time.</p><p><strong>Note</strong>: This principle of reference counting mostly applies to classes. Because, when you pass around an instance of a class in your code, you’re passing around a memory reference, which means that multiple objects point to the same memory address.</p><p>When you’re passing around value types, the value is copied. This means that the retain count for a value type is typically always one; there is never more than one object pointing to the memory address of a value type.</p><h3>ARC vs Garbage Collection</h3><p>If you use a low-level language like C, you’re required to manually free memory you’re no longer using yourself.</p><p>Higher-level languages like Java and C# use something called <strong>garbage collection</strong>. In that case, the runtime of the language will search your process for references to objects, before cleaning up those that are no longer in use.</p><p>ARC unlike GC supports <strong>deterministic finalization</strong> but cannot deal with <strong>reference cycles</strong>. In my opinion, once you understand weak references and how they work to break <strong>reference cycles</strong>, ARC wins out as the superior option for <strong>performance</strong>, <strong>predictability</strong> and <strong>reducing race conditions</strong>.</p><h4><em>Deterministic Finalization</em></h4><ul><li>In ARC, When an object’s reference count reaches zero, Swift calls <strong>deinitializer before removing an object from memory.</strong></li><li>Much like init is a special method in class initialization, deinit is a special method that handles deinitialization.</li><li>What you do in a deinitializer is up to you, an instance is not deallocated until after its deinitializer is called.</li></ul><h3>Reference Cycle</h3><p>All this talk of the heap, stack, GC, ARC is good, but now, you’ll see ARC and the reference cycle in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vLKC3OZdRiEO-ceRZWG9A.png" /></figure><p>I’ll use <strong>author</strong>, <strong>b<em>ook</em></strong> and <strong>editor</strong> classes to demonstrate a reference cycle. Both the <strong>author</strong> and the <strong>editor</strong> have their list of books. and the <strong>book</strong> is linked to the <strong>author</strong> and <strong>editor</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cs2VIXlNUooba73_8dm5dQ.png" /></figure><p>Create an <strong>author </strong>instance<strong> </strong><em>Mustafa Mahmoud (</em>a great Egyptian doctor, philosopher and author)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxYM0eIX3zFAsdwnzaz1yA.png" /></figure><p>A <strong>book </strong>instance<strong> </strong><em>Dialogue with an atheist</em> for the <strong>author</strong> (BTW, it’s a nice book to read)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9aPxa8JqbZaBGh5FiJZyA.png" /></figure><p>An <strong>editor </strong>instance<strong> </strong><em>Waley.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDs9khSFe-Org1T6ck5qlg.png" /></figure><p>Assign the <strong>editor</strong> to the <strong>book.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JyCoPA64ElL8phsLRc0nig.png" /></figure><p>Add the <strong>book</strong> to the <strong>editor’s</strong> list of books.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PL8prcINmHZH8x4GkEpxEQ.png" /></figure><p>and add the <strong>book</strong> to the <strong>author’s</strong> list of books too.</p><p>This is typical publishing house data model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RxXIjqNI1n-5jzHOZ3JQPA.png" /></figure><p>Then, let’s put them all in scope so that as soon as they go out of scope the references to the <strong>book</strong>, <strong>editor</strong> and <strong>author</strong> should drop to zero and deallocate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bcq6xef5ri8c0Mp-4J-kg.png" /></figure><p>The problem here is that at end of the scope, the references of the <strong>book</strong>, <strong>editor</strong> and <strong>author</strong> never drop and reach zero.</p><p>🤔 WHY?! Because book and author have a reference to each other and each instance keeps the other one alive, same as for book and editor.</p><p>And we made things worse by ending the scope, the stack list items will be deallocated and there are no more references to the initial objects.</p><p>This is a classic case of a reference cycle, which leads to a software bug known as a <strong>memory leak</strong>. With a memory leak, memory isn’t freed up even though its practical lifecycle has ended.</p><p>Reference cycles are the most common cause of memory leaks.</p><p><strong>Note:</strong> ARC handles reference counting for you automatically but it’s important to watch out for reference cycles.</p><p><strong>Note: </strong>reference cycle is called “retain cycle” in some books and online resources. both refer to the same thing!</p><h3>Memory Leak</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*DN4Vo3uW8uHfkuIgZNNNWw.png" /></figure><h4>Memory Leaks are BAD!</h4><p>A memory leak is a memory that was allocated at some point but was never released and is no longer referenced by your app. Since there are no references to it, there’s no way to release it and that memory location cannot be used again.</p><p>We all create leaks at some point, from newbies to senior engineers. It doesn’t matter how experienced we are.</p><p>It is paramount to eliminate them to have clean and crash-free apps.</p><p>Memory leaks might not appear until the app has been running a long time. (A memory leak is often like a slow leak in a car tire. Leave it a few hours and there’s no sign of a problem. Leave it a week and your car is grounded).</p><h4><strong>Increases App’s Memory Footprint</strong></h4><p>Memory leaks increase memory footprint by not releasing the abandoned objects. Those objects are garbage. As the action that creates those objects are repeated, the occupied memory will grow.</p><h4><strong>Introduces Unwanted Side Effects</strong></h4><p>Imagine an object that starts listening to a notification when it is created, inside its initializer. It reacts to it, altering the database, playing a video, or posting events to an analytics engine. Since the object needs to be balanced, we make it stop listening to the notification when it is released, inside deinit.</p><p>If this object leaked, the deinitializer is not called: It will never die and never stop listening to the notification. Each time the notification is posted, the object will react to it. If the user repeats an action that creates the object in question, there will be multiple instances alive. All those instances responding to the notification and stepping into each other.</p><p>In these cases, you’ll wish for a crash!</p><h4>Where Leaks Come From?</h4><p>Leaks may come from a 3rd party SDK or framework. Even from classes created by Apple too like CALayer or UILabel. In those cases, there isn’t much we can do, except waiting for an update or discarding the SDK.</p><p>But it is much more likely that we introduce leaks in our code 😅.</p><h3>Where to Go From Here?</h3><p>In this article, you’ve learned about memory regions, data types, reference cycles in classes and memory leaks.</p><p>In the next part of the series <a href="https://blog.devgenius.io/memory-management-part-2-reference-cycles-closures-and-debugging-59b917dc064b#ce92-869979fd6b4b"><strong>Part 2: Reference Cycles, Closures and Debugging</strong></a>, you’re going to learn about breaking reference cycles in both classes and closures, Xcode memory debugger and how to locate leaks using Apple’s Malloc library.</p><p>I hope you enjoyed this article. If you have any question or comment, don’t hesitate, just drop them down here 🤗.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=884c231f5135" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/memory-management-part-1-regions-types-and-leaks-884c231f5135">Memory Management Part 1: Regions, Types and Leaks</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The SOLID Misconceptions]]></title>
            <link>https://medium.com/series/the-srp-misconception-ddf41a672485?source=rss-365ab7d62766------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddf41a672485</guid>
            <dc:creator><![CDATA[Yahya Saddiq]]></dc:creator>
            <pubDate>Sun, 27 Dec 2020 17:04:24 GMT</pubDate>
            <atom:updated>2020-12-28T12:12:13.907Z</atom:updated>
            <content:encoded><![CDATA[<h3>SRP seems the simplest SOLID principle. Unfortunately, it’s the least understood among juniors, seniors, and leaders (including myself 1 week ago).</h3><p>It’s easy to assume that SRP means that every module/class/method should do one thing. There’s a principle for that, and it’s used when refactoring large functions into smaller functions, but it’s not one of the SOLID principles.</p><p>Uncle Bob defined SRP perfectly in his book (Clean Architecture) “A module should be responsible to one, and only one, actor”. SRP should be about future change(s) to the classes/methods rather than present.</p><p>For example, an Employee class with 2 specific methods(calculatePay, reportHours), each does only one thing, violates SRP.</p><p>Let me know if you are interested in an article to demonstrate how the Employee class violates SRP and how to fix it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddf41a672485" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your apps’ memory footprint]]></title>
            <link>https://medium.com/series/your-apps-memory-footprint-ad6921a9e22?source=rss-365ab7d62766------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad6921a9e22</guid>
            <dc:creator><![CDATA[Yahya Saddiq]]></dc:creator>
            <pubDate>Sun, 27 Dec 2020 16:52:09 GMT</pubDate>
            <atom:updated>2020-12-27T16:52:09.265Z</atom:updated>
            <content:encoded><![CDATA[<h3>You as a mobile software engineer always should be conscious of your app’s memory footprint. Its highly recommended to inspect Xcode Memory Graph before delivering a fix or new feature for your app or framework.</h3><h4>This will help you identify memory leaks and retain cycles fixing bugs caused by memory leaks or retain cycles is tedious, so it’s better to pin them down before they occur.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad6921a9e22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in Swift]]></title>
            <link>https://medium.com/series/concurrency-in-swift-a2e11b4a9633?source=rss-365ab7d62766------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2e11b4a9633</guid>
            <dc:creator><![CDATA[Yahya Saddiq]]></dc:creator>
            <pubDate>Sun, 27 Dec 2020 13:25:54 GMT</pubDate>
            <atom:updated>2020-12-27T17:12:59.524Z</atom:updated>
            <content:encoded><![CDATA[<h3>Always start by looking at your problem and try to solve it in the simplest way possible. Let the problem drive the solution not the other way around.</h3><p>When you have a group of a asynchronous jobs that you need to execute them before (updating UI, post notification, etc.). Don’t toss them into a queue right away, there is an easier way for that. Dispatch Group is built for this exact scenario.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2e11b4a9633" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Customize Your Xcode Build Process]]></title>
            <link>https://blog.devgenius.io/how-to-customize-your-xcode-build-process-461749eacea4?source=rss-365ab7d62766------2</link>
            <guid isPermaLink="false">https://medium.com/p/461749eacea4</guid>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[build-phase]]></category>
            <category><![CDATA[provisioning-profile]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[scripting]]></category>
            <dc:creator><![CDATA[Yahya Saddiq]]></dc:creator>
            <pubDate>Sat, 18 Jul 2020 09:15:56 GMT</pubDate>
            <atom:updated>2020-07-18T09:15:56.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Photo by Jared Arango on Unsplash" src="https://cdn-images-1.medium.com/max/1024/1*Ft3HgOHLFehX8oFRZ8DZBA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jaredrossarango?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jared Arango</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When you hit <strong>⌘B</strong> to build your project, Xcode starts a complicated process that begins with the set of text files, resources, and configuration files that constitute your program, and ends with the production of an executable application.</p><p>Xcode offers the possibility to run user-defined code as part of the build process using the <strong>Run Script Phase</strong> in the <strong>Build Phases</strong> section. The invaluable thing about build phases is that you can add your own.</p><p>You can add a <strong>Run Script Phase</strong>, which instructs Xcode to run a command-line script, such as a Shell, Ruby or Python script, at a given point in the build.</p><p>In this tutorial, you will add shell script to your project to:</p><ul><li>Ensure the required tools are available.</li><li>Watermark your app icon with the version, branch and commit hash.</li><li>Copy certain resources into specific target directories.</li><li>Warn if the provisioning profile is expiring soon.</li></ul><h3>Ensuring The Required Tools Are Available</h3><p>A common use of run script build phases is to integrate third-party tools into the build process. But what happens when such tools are not present in the developer’s machine?</p><p>It is a good idea to fail the build and inform your new team members that their setup is incomplete.</p><p>Your first script will show a warning or error if <strong>Swiftlint</strong> is not installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESino6iAHCg5QtiDiK3GMg.gif" /></figure><p>You can access the <strong>Build Phases</strong> by:</p><ol><li>Select your application in the main navigator pane.</li><li>Select the main app target.</li><li>Then, choose the <strong>Build Phases</strong> from the list of tabs at the top.</li></ol><p>Create a <strong>New Run Script Phase </strong>and the below script to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/627f7e0f126dfdfb2528b93f970c9966/href">https://medium.com/media/627f7e0f126dfdfb2528b93f970c9966/href</a></iframe><p>If you prefer warning instead of an error, use the below script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b47792b89ec0d1da762bbc7130a3b2e/href">https://medium.com/media/0b47792b89ec0d1da762bbc7130a3b2e/href</a></iframe><h3>Modifying Your App Icon</h3><p>Another useful use of a custom build phase is to add a watermark to your app icon with the version number, branch name and commit hash.</p><p>To do this, add a <strong>New Run Script Phase</strong> where you retrieve the version number, branch name and commit hash with the following commands:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74661bfe1ed04da28d0e59cbfbb29a1a/href">https://medium.com/media/74661bfe1ed04da28d0e59cbfbb29a1a/href</a></iframe><p>After that, you can edit the app icon using <strong>ImageMagick</strong>. For a complete example, check out this article: <a href="http://merowing.info/2013/03/overlaying-application-version-on-top-of-your-icon">http://merowing.info/2013/03/overlaying-application-version-on-top-of-your-icon</a></p><p>Next, you’ll use build phases to copy resources into a specific target directory.</p><h3>Managing Your App Resources</h3><p>Imagine fixing a bug in an app that has a large splash video, wherein every starts the app shows this video. 😒 It is annoying, right?!.</p><p>With Run Scripts you can control which files Xcode copies to the bundle depending on the currently active configuration, without the need to create a new target.</p><p>To do this, create <strong>RunScriptResources </strong>directory in your root app folder and add both debug(short) and production(long) splash videos, then add the below script to a <strong>New</strong> <strong>Run Script</strong> <strong>Phase</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24fbded729f56e9e83fb69986d7c0730/href">https://medium.com/media/24fbded729f56e9e83fb69986d7c0730/href</a></iframe><p>The above script copies specific video file from your <strong>RunScriptResources </strong>directory<strong> </strong>to the app files directory based on the build type.</p><p>Finally, in the next section, you’ll use the <strong>Run Script Phase </strong>to throw a warning if your provisioning profile is expiring soon.</p><h3>Warning for Provisioning Profile Expiry</h3><p>If you are not using Xcode’s <strong>Automatically manage signing</strong> feature and managing the app signing manually because of the continuous integration environment or for any other reason.</p><p><strong>Run script Phase</strong> becomes very handy to customize your Xcode build process and throw a warning or error before the provisioning profile expires.</p><p>It is important to remember keeping those provisioning profiles always up-to-date so that the build process would not fail at inappropriate times.</p><p>For example, when you are ready to ship a new release but the build is failing due to an expired provisioning profile. At the same time, you are unable to update this provisioning profile on the remote build machine because the admin is on a vacation 😩 (this is from my personal experience). At that point, you start to re-think your signing process 🤔.</p><p>It is always better to use the <strong>Automatically manage signing</strong> feature, but if that’s not an option, <strong>Run Script Phase</strong> is your saviour.</p><p>Create a new <strong>Run Script</strong> <strong>Phase</strong> and add the below script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee815c8c69bcc4d6de8e6d07534bc9d3/href">https://medium.com/media/ee815c8c69bcc4d6de8e6d07534bc9d3/href</a></iframe><p>Here’s what’s happening at each of the numbered comments in the above code:</p><ol><li>Extracts the name and expiry date from the provisioning profile plist.</li><li>Converts expiry date to a YYYYMMDD format.</li><li>Generates current date and current date +15 days.</li><li>Generates current day name and checks if it is not a weekend (you don’t want to bother admins on their free days, right 🤨?!).</li><li>Xcode will show a warning if today +15 days is a <strong>g</strong>reater than or <strong>e</strong>qual the profile expiry date.</li></ol><p>Or you can tell Xcode to show error and stop the building process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5ee51f9740bb13058dfae996f7e3a36/href">https://medium.com/media/e5ee51f9740bb13058dfae996f7e3a36/href</a></iframe><p>Awesome 🥳, no more build will fail due to the provisioning profile.</p><p>Next, you’ll learn some of the tips to create and maintain your scripts 😎.</p><h3>Run Script Phase Tips</h3><p>As with all software, run scripts phases don’t usually come out right at the first try (<em>at least not for me</em>). Here are four tips:</p><h4>Name Your Scripts</h4><p>Xcode will name every new run script phase as <em>Run Script</em>, but that can be quite confusing when you have more than one. Double click on the Run Script header to reveal a text field you can use to rename your phase.</p><h4><strong>Extract The Scripts</strong></h4><p>Writing and editing a script in a text area this size is not ideal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUEFCMbMA8JpT1V7AKyOAQ.png" /></figure><p>Even worse is the way Git tracks the scripts in the project file. It is hard to review them when you or your teammates make changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNAJS6hcnsvULLnIKhybXA.png" /></figure><p>To improve your build scripts, extract them into external files.</p><p>Create a <strong>BuildPhases </strong>directory in your project’s root, then create check_provisioning_profile_script.sh file. Copy its content from the Xcode build phase editor you created earlier.</p><p>Then, make your script executable by <a href="https://bash.cyberciti.biz/guide/Setting_up_permissions_on_a_script">changing its permission</a> using the below command in the terminal:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed79b3afb36fe38a76e23e05a06ac1c8/href">https://medium.com/media/ed79b3afb36fe38a76e23e05a06ac1c8/href</a></iframe><p>Finally, you can replace the script content in the Xcode build phase editor with a command to execute your script:</p><p>$SRCROOT/BuildPhases/check_provisioning_profile_script.sh</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lHiWUvb7lXEzJxfprvlgg.png" /></figure><p>Great, now you and your teammates will edit the script itself, not the project.pbxproj. Reading or reviewing scripts becomes easier 👍🏽.</p><h4>Report Errors</h4><p>You can use echo &quot;error: message&quot; and echo &quot;warning: message&quot; to log extra information. This will help you to debug your issues in the script.</p><h4>Show Environment Variables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U44nfXMEryIR443NZSJjfg.png" /></figure><p>Make sure the <strong>Show environment variables in build log</strong> checkbox is active. This will make Xcode print all the environment variables values if a build fails, and you’ll be able to verify whether the assumptions you made on those are correct or not.</p><h3>Where to Go From Here?</h3><p><strong>Run Script Phase</strong> is very useful Xcode tool. It helps you to automate many tasks, improve the quality of your codebase and make your team’s life easier.</p><p>To learn how to write Bash scripts. <a href="https://ryanstutorials.net/bash-scripting-tutorial">Ryan’s tutorials</a> website is a great place to learn it as a series of small and easy to manage steps.</p><p>I hope you enjoyed this tutorial. If you have any questions or comments, please drop it down here 🤗.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=461749eacea4" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/how-to-customize-your-xcode-build-process-461749eacea4">How to Customize Your Xcode Build Process</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>