<?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 André Gimenez Faria on Medium]]></title>
        <description><![CDATA[Stories by André Gimenez Faria on Medium]]></description>
        <link>https://medium.com/@Andgfaria?source=rss-b971b5916f51------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z51tOBWI_qSoXRGyHuNjqA.jpeg</url>
            <title>Stories by André Gimenez Faria on Medium</title>
            <link>https://medium.com/@Andgfaria?source=rss-b971b5916f51------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 09:04:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Andgfaria/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[Evitando retenções cíclicas em Swift]]></title>
            <link>https://medium.com/mackmobile/evitando-reten%C3%A7%C3%B5es-c%C3%ADclicas-em-swift-3c793b927bac?source=rss-b971b5916f51------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c793b927bac</guid>
            <category><![CDATA[apple-developer-academy]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mackenzie]]></category>
            <dc:creator><![CDATA[André Gimenez Faria]]></dc:creator>
            <pubDate>Fri, 08 Feb 2019 20:36:08 GMT</pubDate>
            <atom:updated>2019-02-08T20:36:08.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJcnblB4L_ZF9ROhw5MVRw.png" /></figure><p>Se você está interessado em desenvolver um aplicativo para iOS de alta performance, mais cedo ou mais tarde você terá que pensar em como os seus componentes estão consumindo a memória disponível e como você pode otimizá-los.</p><p>Um problema comum relacionado a memória é o de retenção cíclica. Mas antes de definirmos o que é uma retenção cíclica, que tal revisarmos um pouco de como o iOS gerencia a sua memória?</p><h3>ARC</h3><p>O método de gerenciamento automático de memória utilizado pela Apple é o ARC (<em>Automatic Reference Counting). </em>Como o nome diz, o número de referências é utilizado para definir se um bloco de memória deve ou não ser desalocado.</p><p>Quando um objeto é criado, sua contagem de referências começa em 1 e vai aumentando conforme o objeto é referenciado. Quando uma referência a esse objeto deixa de ser referenciado, a contagem diminui. Por fim, quando ela chega a 0, o objeto é desalocado da memória.</p><p>Um exemplo desse ciclo de vida pode ser visto abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vy54VZkKuf4zbd7WjdS75Q.png" /><figcaption><a href="https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html#//apple_ref/doc/uid/10000011i">https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html#//apple_ref/doc/uid/10000011i</a></figcaption></figure><h3>Referências fortes e fracas</h3><p>Bom, agora é um bom momento de explicar o que são referências fortes e referências fracas. Na declaração de uma variável é definido se ela é forte ou fraca, sendo forte por padrão.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fd600b3aae23aa978be5265acf8541f/href">https://medium.com/media/8fd600b3aae23aa978be5265acf8541f/href</a></iframe><p>Variáveis fortes incrementam a contagem de sua referência. Por exemplo, se um objeto está com 2 referências e é atribuído para uma nova variável forte, ele passará a ter 3 referências.</p><p>Já variáveis fracas não incrementam essa contagem. Se um objeto está com 2 referências e é atribuído para uma variável fraca, ele continuará com 2 referências.</p><p>Na prática, isso significa que é garantido que, enquanto uma variável forte está ativa, o componente referenciado permanecerá em memória. Já para o caso da variável fraca, não há garantia que, durante o seu ciclo de vida, o componente referenciado sempre existirá.</p><h3>Retenções cíclicas e memory leaks</h3><p>Provavelmente você já deve ter visto alguma modelagem em que uma entidade A pode ter múltiplas instâncias de entidade B e que cada instância da entidade B está associada à uma entidade A. Por exemplo, um livro pode ter várias páginas mas cada página está associada a apenas um livro.</p><p>Em uma implementação bem simplificada, esses modelos poderiam ficar assim:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78a2841e1ac7a5d25e5c8a55d32d681a/href">https://medium.com/media/78a2841e1ac7a5d25e5c8a55d32d681a/href</a></iframe><p>Aparentemente, tudo certo, né? Errado!</p><p>Repare que o livro tem uma referência forte para as páginas e a página tem uma referência forte para o livro. O que você acha que acontece agora? Isso mesmo, um <em>memory leak.</em></p><p>Um <em>memory leak</em> ocorre quando um conteúdo permanece na memória mesmo após deixar de ser utilizado pelo aplicativo.</p><p>No caso do livro e da página, o <em>memory leak</em> é causado por duas referências fortes que se referenciam. A esse problema chamamos de retenção cíclica (<em>retain cycle</em>).</p><p>Explicado o problema, vamos entender agora algumas soluções.</p><h3>Structs e Classes</h3><p>Uma escolha entre usar uma struct ou usar uma class pode ou não causar uma retenção cíclica.</p><p>Tanto structs quanto classes podem ter constantes, variáveis, funções. Ambas podem adotar protocolos. Então, qual a diferença entre elas?</p><p>A maior diferença entre elas é que structs utilizam passagem por valor e classes utilizam passagem por referência. Tá, mas o que isso significa?</p><p>Na passagem por valor, o conteúdo de uma variável é copiado e atribuído a outra variável, mantendo a variável original intacta.</p><p>Olhe o código abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e729e1ce2518b151cbd43b3930b776d0/href">https://medium.com/media/e729e1ce2518b151cbd43b3930b776d0/href</a></iframe><p>Em um playground, temos a seguinte saída:</p><pre>Element(name: “A”, number: 1)<br>Element(name: “B”, number: 2)</pre><p>Mesmo gerando a segunda variável a partir da primeira e depois alterar os seus valores, a variável original continua intacta. Isso ocorre porque a segunda variável é uma cópia da primeira.</p><p>Agora, na passagem referência, ao atribuir uma variável a outra variável, a segunda não é uma cópia da primeira e sim sua nova referência. Isso significa que se alterarmos uma das variáveis, a outra refletirá a mesma mudança.</p><p>E se usarmos uma class em vez de uma struct?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66286678d12fc2ca964f92c6b855873c/href">https://medium.com/media/66286678d12fc2ca964f92c6b855873c/href</a></iframe><p>Agora a saída passará a ser:</p><pre>Element(name: B, number: 2)<br>Element(name: B, number: 2)</pre><p>Note que agora, efetuando os mesmos passos, ambas as variáveis passaram a ter os mesmos valores. Ou seja, a variável original foi modificada.</p><p>Ok, mas por que a passagem por valor e a passagem por referência seriam tão importantes?</p><p>Lembra daquele papo de que precisamos decidir se usarmos structs ou classes e que isso pode gerar memory leaks?</p><p>Então, e se usarmos structs no exemplo do livro e da páginas?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/902fc647697f61b46dda4ec92239ef21/href">https://medium.com/media/902fc647697f61b46dda4ec92239ef21/href</a></iframe><p>Dessa forma não haverá um problema de referência cíclica porque o livro armazenado na página será uma cópia do livro passado no construtor.</p><p>Também podemos continuar usando classes para esse casos mas utilizando uma variável fraca:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b09cef1426f8af7d68e77c0c56c9032a/href">https://medium.com/media/b09cef1426f8af7d68e77c0c56c9032a/href</a></iframe><p>Assim, o livro armazenado na página torna-se um opcional, já que em algum momento ele pode ficar nulo.</p><h3>Protocols</h3><p>Protocols são amplamente usados em Swift e podem ser adotados por classes, structs e enums. Porém, em alguns casos, se não forem tomados alguns cuidados, também podem ocorrer problemas de retenção cíclica com eles.</p><p>Imagine um delegate genérico assim:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aab99d9a1310fa65a55ad522b66619f1/href">https://medium.com/media/aab99d9a1310fa65a55ad522b66619f1/href</a></iframe><p>Nesse caso a variável delegate da ListViewController é do tipo forte e pode ser atribuída para qualquer tipo que conforme com seu protocolo. Porém, por ser uma variável forte, dependendo da implementação, pode ocorrer um risco de retenção cíclica. E como minimizar esse risco?</p><p>Poderíamos usar uma variável fraca, mas se usarmos a keyword weak no código acima teremos um erro de compilação, pois structs e enums não são compatíveis com variáveis fracas. E agora?</p><p>Bom, quando declaramos um protocolo, é possível especificar que eles só poderão ser implementados por tipos de classes. Dessa forma, podemos utilizar variáveis fracas normalmente.</p><p>Ficaria assim:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5cf31dc417f83175b573950d0d7a95e/href">https://medium.com/media/d5cf31dc417f83175b573950d0d7a95e/href</a></iframe><h3>Closures</h3><p>Closures são um dos recursos mais robustos de Swift mas também não são imunes à problemas de retenção cíclica.</p><p>Closures podem ocasionar retenções cíclicas por uma simples razão: por padrão elas referenciam as classes nas quais são chamadas de maneira forte.</p><p>Abaixo temos um exemplo de retenção cíclica com closures:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0206248ceb9af58436b0e6a72980e3f/href">https://medium.com/media/c0206248ceb9af58436b0e6a72980e3f/href</a></iframe><p>Aqui a class tem uma referência forte para a closure e a closure, por padrão, uma referência closure para o objeto da class.</p><p>E como tratar esse comportamento das closures?</p><p>Existem duas maneiras de tornar a referência ao objeto da classe das closures uma referência fraca. A primeira é usar <strong>[unowned self]</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96d7684bf61a88c0716c21adde82491e/href">https://medium.com/media/96d7684bf61a88c0716c21adde82491e/href</a></iframe><p>Agora a closure não possui mais uma referência forte. Porém, tome cuidado ao usar <strong>[unowned self]</strong>, pois se a closure for chamada e depois o seu objeto ser deslocado, ocorrerá um crash no seu aplicativo.</p><p>A segunda maneira é usar <strong>[weak self]</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/385d213b3fd7e11448e27a867f23ef82/href">https://medium.com/media/385d213b3fd7e11448e27a867f23ef82/href</a></iframe><p><strong>[weak self]</strong> funciona da mesma maneira que <strong>[unowned self]</strong>, porém ele trata a referência ao objeto como um opcional.</p><p>Se você já chegou aqui, já sabe o básico sobre como tratar referências cíclicas em Swift. Lembre-se dessas dicas quando for declarar variáveis, protocolos e implementar closures e evitará muitos problemas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*gn_wraovQ0Kj30y9QPX_-Q.png" /></figure><p>Sou o André. Um desenvolvedor mobile apaixonado por tecnologia. Para qualquer dúvida ou sugestão, estou por aqui.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c793b927bac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mackmobile/evitando-reten%C3%A7%C3%B5es-c%C3%ADclicas-em-swift-3c793b927bac">Evitando retenções cíclicas em Swift</a> was originally published in <a href="https://medium.com/mackmobile">Apple Developer Academy | Mackenzie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Swift Tips I]]></title>
            <link>https://medium.com/@Andgfaria/quick-swift-tips-i-7a27efca5524?source=rss-b971b5916f51------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a27efca5524</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[tricks]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[André Gimenez Faria]]></dc:creator>
            <pubDate>Mon, 23 Jul 2018 12:25:20 GMT</pubDate>
            <atom:updated>2018-07-23T12:25:20.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5KaZGVkx12TeIMjpMlGHg.jpeg" /><figcaption><a href="https://unsplash.com/photos/PaBnxI25KYk">https://unsplash.com/photos/PaBnxI25KYk</a></figcaption></figure><p>This post will be a small experiment. How about some Swift tidbits in between the larger stories? Let&#39;s see how it goes!</p><h4>Defer on inits</h4><p>It is very common to use didSet blocks in properties. However, these blocks are not called when the properties are set in an initializer.</p><p>Well, if in your logic it makes sense to update those variables right in the initialization, you can handle this behavior by simply using a defer. Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*fZbzsZBvyoCf1SgZRkvrTA.png" /><figcaption><a href="https://gist.github.com/Andgfaria/7654025859a31dcee8805a5b94e0059f">https://gist.github.com/Andgfaria/7654025859a31dcee8805a5b94e0059f</a></figcaption></figure><h4>Dictionaries as one-line switch / cases</h4><p>Technically, you can rewrite a switch case block into a single line using a dictionary.</p><p>First, create a dictionary in which each pair will have the case condition as a key and its corresponding return as a value. Finally, since a dictionary may or may not have a key in runtime, we use the nil coalescence operator to handle the default case.</p><p>For example, look how we convert a switch case returning a cell height with its IndexPath:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZEdbt94nSQKvFD-b8xxcgA.png" /><figcaption><a href="https://gist.github.com/Andgfaria/bc389e5fcb3bf48969ae1c809ba32462">https://gist.github.com/Andgfaria/bc389e5fcb3bf48969ae1c809ba32462</a></figcaption></figure><p>Naturally, this type of rewriting will depend on how complex your previous logic was. Also, keep in mind, not always one-liners are the best option. You should always prioritize code readability. But, it is always nice to have another option.</p><h4>Variadic Parameters</h4><p>Variadic parameters are function parameters which behave just like constant arrays but expressed in a different way when being called. Instead of using the array notation, the passed elements are separated by commas.</p><p>If you want to build your own function using these parameters, simply declare the type of the parameters followed by 3 dots.</p><p>For example, look this simple UIView extension to add multiple subviews in a single call:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*yPSi9tWnWBDhSoFlIi8qCA.png" /><figcaption><a href="https://gist.github.com/Andgfaria/20839237e5b06caeb9fc1709c9b9f51f">https://gist.github.com/Andgfaria/20839237e5b06caeb9fc1709c9b9f51f</a></figcaption></figure><p>Here we can pass as many parameters as we would like. However, there can be only one variadic parameter per function.</p><p>I hope you enjoyed this quick tips. Maybe, if everything turns out right, there will be more to come! We&#39;ll see…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*CmAEbUc8YjhzBACSshNCZg.png" /></figure><p>I am André. A young brazilian mobile developer that loves everything related to technology. If you have any doubt or suggestion, feel free to contact me here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a27efca5524" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My take on Coded Views]]></title>
            <link>https://medium.com/mackmobile/my-take-on-coded-views-ae5fea66642?source=rss-b971b5916f51------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae5fea66642</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[viewcode]]></category>
            <category><![CDATA[programming-pattern]]></category>
            <category><![CDATA[protocol]]></category>
            <dc:creator><![CDATA[André Gimenez Faria]]></dc:creator>
            <pubDate>Mon, 08 Jan 2018 10:44:40 GMT</pubDate>
            <atom:updated>2018-01-11T16:11:59.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qG3JqYQxXvRhXSR3stefw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/CrE4LzakN8Y?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Koby Kelsey</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When building an iOS app there are multiple ways in which you can create the UI. You can use Storyboards and Xibs or create all components on runtime. Each approach has advantages and disadvantages and, in the end, it will all come up to the team goals and preferences.</p><p>However, no matter what you choose, it is extremely important to make sure everyone in the team follows the same style and organization. You don&#39;t want a giant, messy storyboard or dozens of View Controllers without a consistent pattern.</p><p>That is why I experimented and created a simple, handy protocol to control the order in which my UI components are created in all my classes. This is far away from being a complete framework, but gets the job done and is pretty consistent. I call it the ViewCodable protocol.</p><p>This protocol consists of just a few methods which are called in a specific order. Here is its declaration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/988423cfbfbf979d5843eb49d9163cfc/href">https://medium.com/media/988423cfbfbf979d5843eb49d9163cfc/href</a></iframe><p>You might wonder now: how is this protocol easy to use if there are so many methods to worry about?</p><p>Well, thanks to Swift extensions , all these methods have default implementations. In fact, some of those methods initially do nothing, making them optional in most cases.</p><h3>And what does each method do?</h3><pre>func setup(with views : [UIView])</pre><p>This is the main setup method. The argument is the list of views you wish to add to the views hierarchy and it will run all the other methods. I usually call it in the viewDidLoad function of UIViewControllers or in the initializers of custom UIViews .</p><pre>func addToHierarchy(_ views : [UIView])</pre><p>Here we lay down the work to actually add the views to the hierarchy. Thanks to a neat protocol oriented programming trick, where the views are actually going to be added depends on the kind of component you use. For example, if the component is a subclass of UIView , the views will be added to itself. If the component is a subclass of UIViewController the views will be added to its view property. Last, but not least, if the component is a subclass of UITableViewCell the views will be added to its contentView property.</p><p>Furthermore, you can extend the protocol and add default implementations for other kinds of components.</p><pre>func setupConstraints()</pre><p>This method is pretty straightforward. Here you can enable your Autolayout constraints or adjust your views frames manually. Now, how to do it is completely up to you. Maybe some frameworks will come in handy here, right?</p><pre>func setupStyles()</pre><p>This is where you can customize the styles of your views. Change fonts, colors, alignments, texts. Whatever your pick.</p><pre>func bindComponents()</pre><p>When creating interactive components such as buttons or sliders we must manually bind its actions. It could be as simple as adding a selector, or, if you are into reactive programming, enable reactive bindings.</p><p>But, if your setup is not interactive at all, you can simply leave this method as it is.</p><pre>func setupAccessibilityIdentifiers()</pre><p>If you project is not covered by UI tests, than you can leave this method as it is too. If not, then maybe you will find it useful to setup your views&#39; identifiers here.</p><p>This pretty much covers everything the protocol does and how can you use it. Want to see it in a real usage example?</p><h3>Hands on Time!</h3><p>Imagine a simple one-screen app with only a button and a label. You press the button and the label shows a random number between 1 and 100.</p><p>Something just like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*xJwafOtWSZEiZH5pH70rIA.png" /></figure><p>This entire screen was created with a just a few lines of code.</p><p>For instance, this is our ViewController declaration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3053f5430db5dc820fb7853506a81f2b/href">https://medium.com/media/3053f5430db5dc820fb7853506a81f2b/href</a></iframe><p>We just declared our label and a button and called the main setup method.</p><p>Now the important part: how we use the protocol methods. In this case, we will only use the following three: setupConstraints , setupStyles and bindComponents .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b0ac4b7d5b02106e1b291587dfd815e/href">https://medium.com/media/0b0ac4b7d5b02106e1b291587dfd815e/href</a></iframe><p>Both label and button have fixed width and heights and are positioned around the safe area center using constraints. This is what you usually do in Interface Builder, but with code!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f8d20ccf27bed39e805d2fa3af1d2dc/href">https://medium.com/media/7f8d20ccf27bed39e805d2fa3af1d2dc/href</a></iframe><p>For the styles part, I just changed a few properties, like colors, fonts and texts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/139f8572dddd590dc0c4fa729ac06440/href">https://medium.com/media/139f8572dddd590dc0c4fa729ac06440/href</a></iframe><p>Finally, we create a method that generates a random number between 1 and 100 and attach it to our button.</p><p>And that&#39;s it! We have a fully view coded app.</p><p>You can see it by yourself <a href="https://github.com/Andgfaria/ViewCodableExample.git">here</a>. And, if you really like it, <a href="https://gist.github.com/Andgfaria/d1ec5539b0ca0ec2bdd634ee689277bc">here</a> is the full source code of the ViewCodable protocol. You can improve it and use it in your projects.</p><p>So, this is my take on coded views. It might not be better or worse than the way you already do things and it certainly can be improved over time but it already paid off in the projects I have been working on. That is why I thought it was worth sharing. I hope you eventually think it is worth too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*gn_wraovQ0Kj30y9QPX_-Q.png" /></figure><p>I am André. A young brazilian mobile developer that loves everything related to technology. If you have any doubt or suggestion, feel free to contact me here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae5fea66642" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mackmobile/my-take-on-coded-views-ae5fea66642">My take on Coded Views</a> was originally published in <a href="https://medium.com/mackmobile">Apple Developer Academy | Mackenzie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoiding retain cycles in Swift]]></title>
            <link>https://medium.com/mackmobile/avoiding-retain-cycles-in-swift-7b08d50fe3ef?source=rss-b971b5916f51------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b08d50fe3ef</guid>
            <category><![CDATA[advanced]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[cars]]></category>
            <category><![CDATA[apple-developer-academy]]></category>
            <dc:creator><![CDATA[André Gimenez Faria]]></dc:creator>
            <pubDate>Wed, 20 Sep 2017 19:46:36 GMT</pubDate>
            <atom:updated>2017-09-20T19:46:36.027Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMyRF_Z-QUozaovLmvnaUw.png" /></figure><p>If you want to develop a high perfomance iOS app, sooner or later you will have to consider how your components are consuming the memory resources available and how you can optimize then.</p><p>One common problem related to memory management is the retain cycle problem. But before we define exactly what it is, how about seeing how iOS manages its own memory?</p><h3>ARC</h3><p>The automatic memory management method used by Apple is called ARC (Automatic Reference Counting). As its own name says, the reference count is used to determinate whether a memory block should or should not be deallocated.</p><p>When an object is created, its reference count begins with 1. This reference count can increase or decrease during its lifecycle. At last, when the reference count reaches 0, the object is deallocated from memory.</p><p>An example of this lifecycle can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vy54VZkKuf4zbd7WjdS75Q.png" /><figcaption><a href="https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html#//apple_ref/doc/uid/10000011i">https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html#//apple_ref/doc/uid/10000011i</a></figcaption></figure><h3>Strong and Weak References</h3><p>Well, now is a good moment to explain what are strong and weak references. When declaring a variable we define if it is strong or weak. Variables are strong by default.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fd600b3aae23aa978be5265acf8541f/href">https://medium.com/media/8fd600b3aae23aa978be5265acf8541f/href</a></iframe><p>Strong variables increase the reference count. For instance, if an object has a reference count of 2 and is assigned to a new strong variable, its reference count increases to 3.</p><p>On the other hand, weak variables do not increase the reference count. If an object with a reference count of 2 is assigned to a new weak variable, its reference count will still be 2.</p><p>Furthermore, this means that, while a strong variable is active, its referenced component will be guaranteed to remain in memory. However, this guarantee will not apply to weak variables.</p><h3>Retain cycles and memory leaks</h3><p>You have probably seen a model in which an entity A has multiple instances of an entity B and each B entity is associated with an A entity. For example, a book can have many pages and every page belongs to a book.</p><p>In a very simplified implementation, these models could be something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78a2841e1ac7a5d25e5c8a55d32d681a/href">https://medium.com/media/78a2841e1ac7a5d25e5c8a55d32d681a/href</a></iframe><p>So far so good, uh? Well, not so much…</p><p>Can you see that the book has a strong reference to its pages and the page has a strong reference to the book? Guess what happens next. That’s right, a memory leak.</p><p>A memory leak occurs when a content remains in memory even after its lifecycle has ended.</p><p>In this case, the memory leak is caused by two strong variables that address each other. This problem is known as the retain cycle problem.</p><p>Ok, now let’s see some solutions.</p><h3>Structs and Classes</h3><p>A choice between a struct and a class can cause a retain cycle.</p><p>Both structs and classes can have constants, variables, functions and protocols. So, what is their difference?</p><p>The difference is that structs are passed by value and classes are passed by reference. Ok, but what does that mean?</p><p>When a variable is passed by value, its content is copied and assigned to another variable, keeping it intact.</p><p>Take a look at this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e729e1ce2518b151cbd43b3930b776d0/href">https://medium.com/media/e729e1ce2518b151cbd43b3930b776d0/href</a></iframe><p>The output from this is:</p><pre>Element(name: “A”, number: 1)<br>Element(name: “B”, number: 2)</pre><p>Although we created a second variable from the first variable and changed its value, the value from the first one remained the same.</p><p>However, when a variable is passed by reference, the new variable will be a reference to the other one instead of a copy. So, when one of them changes, the other one will follow.</p><p>What happens if we use a class now?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66286678d12fc2ca964f92c6b855873c/href">https://medium.com/media/66286678d12fc2ca964f92c6b855873c/href</a></iframe><p>Then the output will be:</p><pre>Element(name: B, number: 2)<br>Element(name: B, number: 2</pre><p>So, with the same steps, both variables will hold the same value and the original value will be lost.</p><p>Fine! But why we are talking about passing by value and passing by reference after all?</p><p>Well, remember when I told you that the choice between a struct and a class could cause retain cycles?</p><p>Let’s go back to the book and pages examples, but using a struct:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/902fc647697f61b46dda4ec92239ef21/href">https://medium.com/media/902fc647697f61b46dda4ec92239ef21/href</a></iframe><p>Now there won&#39;t be a retain cycle since the book assigned in the initializer will actually be an copy.</p><p>We can also keep using classes, but using a weak variable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b09cef1426f8af7d68e77c0c56c9032a/href">https://medium.com/media/b09cef1426f8af7d68e77c0c56c9032a/href</a></iframe><p>Just remember that now the book will be an optional and eventually it could become nil.</p><h3>Protocols</h3><p>Protocols are widely used in Swift and can be adopted by classes, structs and enums. However, in some cases, if you are not careful enough, they can also cause retain cycles.</p><p>Imagine a generic delegate like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aab99d9a1310fa65a55ad522b66619f1/href">https://medium.com/media/aab99d9a1310fa65a55ad522b66619f1/href</a></iframe><p>The delegate variable in this ListViewController is a strong one and can hold any type that conforms to its protocol. However, what if one this types is a class which has a strong reference to the view controller itself? Risky, right?</p><p>Changing the delegate variable to weak might do the trick, but if you try it you will get a compile error, since structs and enums cannot be assigned to weak variables.</p><p>But fear not, there is still a way! When we declare a protocol we can specify that only class types can adopt it. That way we can use weak variables as usual. Just look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5cf31dc417f83175b573950d0d7a95e/href">https://medium.com/media/d5cf31dc417f83175b573950d0d7a95e/href</a></iframe><h3>Closures</h3><p>Closures are one of the most robust features available in Swift. Yet they are note retain cycle proof.</p><p>Closures can cause retain cycles for a single reason: by default, they have a strong reference to the object that uses them.</p><p>In this example we have a retain cycle with closures:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0206248ceb9af58436b0e6a72980e3f/href">https://medium.com/media/c0206248ceb9af58436b0e6a72980e3f/href</a></iframe><p>This object has a strong reference to the closure and, since we used self in the closure block, the closure has a strong reference to the object itself.</p><p>We can solve this in two ways.</p><p>First, we can use <strong>[unowned self]</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96d7684bf61a88c0716c21adde82491e/href">https://medium.com/media/96d7684bf61a88c0716c21adde82491e/href</a></iframe><p>Now the closure doesn&#39;t have a strong reference anymore. Just be careful when using <strong>[unowned self]</strong> since that, if the object has already been deallocated when the closure is called, a crash will occur.</p><p>We can also <strong>[weak self]</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/385d213b3fd7e11448e27a867f23ef82/href">https://medium.com/media/385d213b3fd7e11448e27a867f23ef82/href</a></iframe><p><strong>[weak self]</strong> achieves the same result as <strong>[unowned self]</strong> but is handled as an optional.</p><p>Great! If you got here, you already know the basics of handling retain cycles in Swift. Remember this tips when declaring variables, protocols and closures and you&#39;ll avoid many problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*gn_wraovQ0Kj30y9QPX_-Q.png" /></figure><p>I am André. A young brazilian mobile developer that loves everything related to technology. If you have any doubt or suggestion, feel free to contact me here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b08d50fe3ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mackmobile/avoiding-retain-cycles-in-swift-7b08d50fe3ef">Avoiding retain cycles in Swift</a> was originally published in <a href="https://medium.com/mackmobile">Apple Developer Academy | Mackenzie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testes? Para quê?]]></title>
            <link>https://medium.com/mackmobile/testes-para-qu%C3%AA-ea3906c2ab48?source=rss-b971b5916f51------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea3906c2ab48</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mackenzie]]></category>
            <category><![CDATA[apple-developer-academy]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[André Gimenez Faria]]></dc:creator>
            <pubDate>Fri, 08 Sep 2017 23:58:48 GMT</pubDate>
            <atom:updated>2017-09-13T13:30:07.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSgS5SstcnEut_8iyEN06w.png" /></figure><p>Como desenvolvedor você provavelmente já se deparou com a seguinte situação: pedem pra você alterar a funcionalidade X, você faz isso, valida que ficou certo e segue adiante. Porém, no dia seguinte, alguém diz que a funcionalidade Y parou de funcionar depois da sua alteração. E era de uma área completamente diferente! Como isso é possível?! Infelizmente, no mundo de desenvolvimento isso é mais comum do que deveria.</p><p>Mas não seria ótimo se houvesse formas de evitar incidentes como esse? Aí você perderia menos tempo consertando coisas que quebraram acidentalmente e passaria mais tempo fazendo coisas que realmente agregassem valor ao seu projeto. Pois bem, existem sim maneiras de prevenir os chamados <em>side-effects</em>. Sabe qual é uma delas? Desenvolver testes para o seu projeto!</p><h3>Legal, mas o que seriam esses testes?</h3><p>Quando programamos geralmente criamos componentes que recebem algum tipo de entrada e executam operações sobre essa entrada para obter algum resultado. Por exemplo, um toque em um botão seria uma entrada para ir para outra tela, uma notificação seria a entrada para ativar um recurso de um aplicativo e assim por adiante.</p><p>Nesse contexto, os testes são rotinas que verificam que, dada uma entrada, a aplicação irá se comportar conforme espero e produzirá um resultado correto. Um teste de uma função de somas validaria que o retorno possui um valor correto. Um teste de inserção de um dado em um banco de dados validaria que as informações salvas sejam consistentes. Um teste de uma função que altera o <em>layout</em> de uma tela validaria que os componentes <em>renderizados</em> estariam com os layouts certos.</p><h3>Entendi. E quais tipos de testes existem?</h3><p>Existem 3 tipos de testes: testes unitários, testes funcionais/integração e testes de interface de usuário. Cada tipo verifica componentes em diferentes níveis de abstração e com diferentes complexidades.</p><h4>Testes Unitários</h4><p>Os testes unitários validam os componentes básicos do seu projeto, como funções, classes e interfaces, de maneira direta e isolada.</p><p>Nesse tipo de teste você não precisa focar se os componentes são utilizados de maneira correta e sim se o componente por si só cumpre o que promete.</p><h4>Testes funcionais ou testes de integração</h4><p>Testes de integração validam que o uso interligado dos diferentes componentes produz o resultado esperado.</p><p>Por exemplo, se o seu projeto consome dados de um web service teríamos um teste para garantir que a conexão com esse web service é efetuada com sucesso e os dados obtidos são tratados como o esperado. Da mesma forma, se salvamos modelos em um banco de dados local, um teste de integração validaria que a persistência de dados funciona.</p><h4>Testes de interface de usuário</h4><p>Os testes de interface de usuário automatizam o uso da sua aplicação em seus cenários reais de uso.</p><p>Por exemplo, um teste pode simular todo o fluxo de cadastro de um aplicativo, simulando a entrada de dados e ações que os usuários normalmente fazem.</p><p>São os testes com maior nível de abstração e maior custo de desenvolvimento, porém garantem que a sua aplicação realmente está funcionando para o usuário.</p><h3>Ok, mas como eu monto um teste?</h3><p>A forma como que um teste é desenvolvido depende muito de sua plataforma, complexidade do componente a ser testado e suas dependências.</p><p>Porém, de maneira geral, um teste passa por 3 etapas:</p><ol><li>A primeira etapa consiste em preparar as entradas necessárias para testar o componente. Nela criamos objetos os objetos necessários, atribuímos os valores iniciais às variáveis, etc.</li><li>Na segunda etapa executamos a função do componente em si.</li><li>Por fim, validamos que, depois que o componente processou as entradas, o componente se comportou corretamente e retornou um resultado esperado. Se sim, o teste passou. Caso contrário, o teste falhou.</li></ol><p>Ok. Vamos botar a a mão na massa? Que tal montarmos testes para essa função que calcula números de Fibonacci?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5cc36e27aff0608bc6309a2492c4d2b/href">https://medium.com/media/f5cc36e27aff0608bc6309a2492c4d2b/href</a></iframe><p>A função tem 2 casos bases: o número de Fibonacci de 0 é 1 e o número de Fibonacci de 1 é 1. Para os demais casos o número de Fibonacci é obtido pelos números anteriores calculados recursivamente até chegarem nos casos bases.</p><p>Para a função ter uma <strong>cobertura de testes</strong> completa, ou seja, para todas as possibilidades tratadas pela função serem validadas por pelo menos um teste, podemos montar 3 testes: um para validar que o número de Fibonacci de 0 é 1, um para validar que o número de Fibonacci de 1 é 1, e, por fim, um para validar que um outro número de Fibonacci, por exemplo, o número 4, é calculado corretamente.</p><p>Note também que a função só aceita números inteiros positivos então não precisaremos testar a função com um valor negativo como parâmetro de entrada.</p><p>Começamos definindo as entradas para cada teste:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72a6b626bca6b50e0d3765fcde402ae0/href">https://medium.com/media/72a6b626bca6b50e0d3765fcde402ae0/href</a></iframe><p>Agora chamamos a função para calcular os fatoriais e armazenamos os resultados em variáveis:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c55ae32e5150f703902cbf40938cf037/href">https://medium.com/media/c55ae32e5150f703902cbf40938cf037/href</a></iframe><p>E depois comparamos as variáveis com os resultados esperados:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18da13ad241a7915f19d704cdab39626/href">https://medium.com/media/18da13ad241a7915f19d704cdab39626/href</a></iframe><p>Por fim, deixando tudo de forma mais sucinta:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b98616d2754f18baebaef2cfb9ce269/href">https://medium.com/media/8b98616d2754f18baebaef2cfb9ce269/href</a></iframe><p>Pronto! Com os testes passando podemos usar essa função nos códigos de produção com a garantia que não teremos problemas.</p><h3>Tá, mas é sempre fácil assim?</h3><p>Para coisas simples, sim. Mas duvido que em seu projeto você vai simplesmente fazer uma função de Fibonacci. Então, quando fizer algo complexo e sentir que está difícil de testar, pense nessas duas dicas:</p><ul><li><strong>Divida componentes complexos em componentes menores</strong> e especializados. É muito mais fácil testar algo menor e com apenas um propósito.</li><li><strong>Priorize interfaces ou protocolos do que componentes concretos</strong>. Assim você pode criar um componente para uso em produção e outro componente com um comportamento simplificado para os testes.</li></ul><p>Outras dicas boas que se aplicam tanto para testes simples quanto complexos são:</p><ul><li><strong>Certifique-se de cada teste está realmente isolado</strong>. Um teste não pode ser afetado por outro.</li><li><strong>Teste apenas os métodos públicos</strong>. Um método privado provavelmente será chamado por outro método público.</li><li><strong>Pesquise sobre <em>mocks</em> e <em>stubs</em></strong>. Eles são tipos de objetos especiais de objetos feitos especialmente para testes.</li><li>Não se preocupe em testar toda a sua base de código. <strong>Foque nas funções mais críticas e complexas</strong>.</li></ul><h3>Nossa, quanta coisa! Vale a pena mesmo tanto trabalho?</h3><p>Desenvolver testes é uma tarefa trabalhosa. Você vai gastar tempo não só implementando as funcionalidades como também nos testes dessas funcionalidades.</p><p>E tempo é dinheiro né? Então, fazer testes só vai aumentar o custo do meu projeto, certo?</p><p>Errado. Os testes vão garantir que o seu produto funciona mesmo após mudanças. Eles garantem que o seu projeto cumpre sua especificação e evitam futuros problemas de regressão, conforme visto <a href="http://ieeexplore.ieee.org/abstract/document/1201238/">aqui</a>.</p><p>Portanto, o custo dos testes gera na verdade um ganho, já que você irá gastar menos tempo resolvendo problemas que aconteceram depois do lançamento do seu produto.</p><h3>Ok. Você me convenceu! Como eu aplico testes no meu processo de desenvolvimento?</h3><p>Uma forma de integrar testes durante o desenvolvimento é utilizar a prática de TDD (<em>Test Driven Development</em>).</p><p>Para aplicá-lo basta executar o seguinte ciclo:</p><ol><li>Escreva um teste que falha.</li><li>Mude o seu código até que o teste passe.</li><li>Melhore o seu código refatorando-o.</li><li>Repita o processo.</li></ol><p>A partir do TDD também surgiu uma metodologia de testes chamada BDD (<em>Behavior Driven Development</em>).</p><p>O BDD segue os mesmos princípios que o TDD com a diferença que esses testes não focam em aspectos técnicos mas sim em cenários de uso do seu produto.</p><p>Esses cenários são descritos em uma linguagem ubíqua. Algo do tipo: &quot;o meu app deve permitir o login via Facebook&quot; ou &quot;se o usuário não possuir saldo ele não pode seguir para o fluxo X&quot;). Com esse tipo de linguagem pessoas sem uma base técnica também podem participar na criação dos testes.</p><p>De qualquer forma, ambas metodologias promovem o desenvolvimento contínuo dos testes. Dessa forma, ao chegar no primeiro entregável do seu projeto ele já estará todo testado e validado.</p><p>Agora que você chegou até aqui e sabe o básico sobre os testes, pense com carinho quando for fazer aquele projeto novo ou evoluir um projeto existente e considere aplicar testes já no desenvolvimento. No futuro você verá que foi uma boa decisão.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*s9HHk3QZzsoqraSikkQbBg.png" /></figure><p>Sou o André. Um desenvolvedor mobile apaixonado por tecnologia. Para qualquer dúvida ou sugestão, estou por aqui.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea3906c2ab48" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mackmobile/testes-para-qu%C3%AA-ea3906c2ab48">Testes? Para quê?</a> was originally published in <a href="https://medium.com/mackmobile">Apple Developer Academy | Mackenzie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>