Menu

One voice. Our voice. Cogent voice.

Tag Archives: iOS

What is Markdown?

Markdown is a lightweight markup language that is natural to write and easy to convert to rich text and other formats such as HTML or PDF. Because of its simplicity and portability, it has become the go-to option for developers to document their codes and README files. Find a random repository on GitHub, you’re likely to see at least one file in it written in Markdown. In addition to developer communities, Markdown is also supported in a variety of other places such as blogs and forums. Even some instant messaging apps now have Markdown-inspired formatting features.

Markdown in GitHub

As one of the most popular places where people use Markdown extensively, GitHub actually has its own version of Markdown syntax which is called GitHub Flavored Markdown (GFM for short). Being a Git hosting service, GitHub uses GFM to provide users additional features such as the ability to reference issues, pull requests and SHA-1 hashes of commits.

Markdown in WordPress

WordPress supports Markdown as well but you have to enable it first in your blogs settings. In Settings under Configure section of the side menu, you can turn on Markdown support for composing in the Writing tab and for comments in the Discussion tab. After saving the settings, you can start to write your new blog posts in WordPress using Markdown. As a matter of fact, this whole blog post is written in Markdown!

Time to play?

Now that you know more about Markdown, let’s see some examples!

Codes

You can either put your code inline like this or add a code block in your file like what I’m going to show you below.

This is a code block!
The syntax for inline code is to wrap your code inside a pair of `.
To use a code block, simply put ``` at the lines above and below your code block.

Also, checkout this awesome post on Ray Wenderlich for some recommendations on Markdown editors for MacOS.

Bonus

Hey, thanks for reading this blog post! Here’s a bonus section for you! Do you know that you can make presentation slides using Markdown as well? I found an interesting presentation writer on GitHub called Marp. Just separate your slides with --- between empty lines and you can literally write a whole presentation using Markdown in a single file!

The other day I came across a bug when I tried to use Key-Value Observing to observe the change of a property in some not-so-modern Objective-C class. The observer was never notified when the property’s value changed. It took me a long time to figure out what was wrong and I just want to share my findings, so you don’t have to be upset should you ever run into a similar situation.

It all started with a simple “@synthesize” statement.

Some background first. In “Adopting Modern Objective-C” document, Apple recommends using properties instead of instance variables (or iVars) in “as many places as possible”. One of the benefits listed is “Auto-synthesized getters and setters”. If you still remember all the “@synthesize” statements in stone-age of Objective-C, I believe you will just love auto-synthesizing feature in modern Objective-C as much as I do. (Almost) No more “@synthesize”! Isn’t that sweet?

Even though synthesizing is no longer required (most of the cases, and usually not even recommended), you can still use it to synthesize a property with a backing iVar (Compiler will create an iVar with the same name of the property if there isn’t one created by developer.) and custom setter and getter. However, if you don’t make your setter KVO-compliant or just simply ignore setter and change backing iVar’s value directly, KVO will obviously fail to observe the change in property’s value.

A well-designed custom setter or a setter created by auto-synthesizing calls “willChangeValueForKey:” and “didChangeValueForKey:” methods at appropriate moments to send observer notifications so that observers that implements KVO methods know when a property is changed. If new value is directly assigned to a backing iVar, the setter is never called and hence there will be no notification sent for KVO. Not only will your own KVO code not work, any framework you may have used in your project that depends on KVO will also not work.

You can find a demo project here. In the demo, if a property’s value is modified without using the accessor (setter in this case), KVO won’t be able to observe the change.

I’ve been involved in iOS development since late 2011. Watching and being part of the rapidly growing app development industry has always been a fascinating thing to me. In this three-part series of blog post, I’ll share with you the way I learn iOS development and some of the habits I developed over the years of iOS development. In the first part of the blog post, I’ll talk about how to get started and some of the resources that have helped me in learning iOS development.

There’re many ways one can find the motivation of starting iOS development. It may be a will to learn something new, a good idea you want to turn into a good app, or you need some features on your phone or computer and you just can’t find any app that meets your demands. For me, it was a project that requires me to complete an unfinished PhoneGap app. Since I knew nothing about mobile app development and the only requirement for the project is to finish it, I went ahead and started to learn iOS development. I personally find it easier to actually learn a programming language with a real project. It doesn’t have to be something big or innovative as long as you have a plan. Most important, you have to stick with your plan and finish the project. I feel completing the project is the key to learn and progress, and in addition, you will have something to play with or show off to your friends when the project is finished.

Learn in Classrooms

I suppose one of the best place to learn stuff is in classroom. But unfortunately I didn’t have the time to take the mobile app development course when I was in college. Instead, I turned to the Internet and started to learn iOS development on iTunes U. There are many useful courses out there on iTunes U and particularly the iPad and iPhone App Development Course from Stanford was the one that helped me to get started. Although I know some people think the course is not really beginner friendly, I still find it helpful and a good course to get a feeling of mobile app development. It is always good to take an actual class but don’t limit yourselves to only physical classrooms. With the Internet, anywhere can be a classroom.

Utilize Tutorials

Developers on the Internet are awesome. They make wonderful frameworks and libraries for us to use and they also make great tutorials for us to learn from. As the old saying goes, Google is your friend. Use Google to discover awesome tutorials that can help you. However, I would suggest to skip Apple’s official tutorials for now and come back later because I found them a little bit more difficult to understand and less detailed. Keep in mind that the tutorials from Apple are still helpful. We will come bacAs beginners, we should look for detailed and preferably step-by-step tutorials. I personally am a big fan of Ray Wenderlich’s tutorial website. They have several teams to make sure their tutorials are high quality and up to date and they cover topics from iOS development 101 all the way to complicated stuff like Open-GL programming.

Another website I find useful is Ry’s Objective-C Tutorial. It’s not a step by step guide but rather an easy-to-understand guide on the Objective-C language. It helped me to understand the basics of Objective-C and reading it from time to time helps me to strengthen my foundation of Objective-C language.

One last thing about utilizing tutorials is the way how we use them. Different people have different styles of following tutorials. For me, I always treat tutorials as if they were real projects. I write the codes with the instructions of tutorials and apply my coding standard to it. I suggest to avoid copying and pasting any code from the tutorial because every time I copied and pasted chunks of codes from tutorials I ended up learning nothing and had to restart the whole tutorial.

Read Documents

I always consider myself as a student and as a student I have to do my readings. In our case as students of iOS development, we have to read documents for SDKs, frameworks, libraries, etc. Study and apply coding style guidelines from Apple and companies such as Google and NYTimes will help us to streamline our coding habits and make the lives easier for “future us” when we come back to our old projects. We all have been in the situations where we look at our codes and wonder if they were actually written by ourselves, aren’t we?

Documents for SDKs, frameworks and libraries are of course equally important and helpful. Now it’s a good time to check out Apple’s official tutorials since we already have a basic understand of what’s going on with iOS development. They (especially the new ones) are great when reading with Apple’s documents. Blogs such as NSHipster can also help us to better understand documents and discover interesting topics that will potentially be useful in the future.

What’s Next?

I think by now we should somehow have an idea of how to get started on iOS development. Feel free to leave a comment to let us know if the blog post is helpful or tell us your story of learning mobile app development. In the next part, I will share with you one habit that has benefited me a lot during my study of iOS development. Remember to check back and happy learning!

This year’s WWDC should be considered as the biggest event for an iOS developer since the release of iPhone OS 2 in 2008. During the conference, Apple introduced a huge number of new development kits as well as many improvements to the existing SDK along with the new iOS8. In addition, Apple also surprised the whole developer community with the introduction of Swift language. As a developer myself, I’ll discuss several things that I’m excited about in this blog post.

iOS8: More power, More possibilities

Back in 2008, Apple introduced the App Store and opened the door to thousands of developers to make all kinds of wonderful apps for the platform. As years go by, the Cupertino based company has gradually enhanced the APIs in iOS SDK to make iOS apps more capable and useful. This year, with the introduction of iOS8 SDK, developers can now do more than they ever could have done. First, let’s start with some fun. Last year, Apple introduced SpriteKit for 2D game development and it has instantly become one of the greatest competitors to the popular 2D iOS gaming framework Cocos2D. This year, in addition to the improvements of SpriteKit, Apple also brought two new 3D gaming frameworks, SceneKit and Metal. Like SpriteKit, SceneKit offers easy ways to create 3D animated scenes in apps. And it even incorporates a physics engine and a particle generator for more complex 3D effects. For more professional 3D game developers, Metal offers the abilities to directly harvest the power from A7 processor’s GPU without going through a layer of Open GL ES. All these new APIs will enable developers to create even better user experiences and awesome graphical effects in different kinds of apps. The gaming related frameworks are just a small part of iOS8 SDK’s improvements. In iOS8, apps can now have more capabilities. Apart from being an iOS developer, I’m also a photographer. Therefore I have to talk about PhotoKit, manual camera controls and extensions introduced in iOS8. As you may have seen in the keynote event of WWDC, developers can now make apps that are able to access iCloud Photo assets directly in Camera roll and share the photos across different apps and platforms. Manual camera controls such as focus, white balance and exposure settings are now provided by AVFoundation framework for apps to use. All of these new features can add up to a pretty good camera app with the already-wonderful camera hardwares in iPhones. Now you may ask what are the extensions and why they are important to a camera app. Extensions are custom functionalities provided by apps that can be accessed within the context of some other user task. And well, they are not only important for camera apps, but also for all kinds of other apps. In our example of a camera app, the app can have a photo editing extension and the user can use that extension to edit any picture in any app. The extension can also incorporate with Notification Center to provide extensive photography related functions. One of the most request feature in iOS now can also be realized by extension. That is custom keyboards. With the ability of extensions, developers can now make keyboards for users to carry out all kinds of specific actions. I wouldn’t be surprised if someone makes a keyboard just for entering camera shutter speeds and exposure stops or, a keyboard dedicated for mathematical equations. Next thing I want to talk about is the CloudKit. iCloud has been there for quite some time. It seems like that this year Apple has finally take the iCloud from a “hobby”to something serious. With CloudKit, iCloud now can act like a web server for app’s data. And features such as authentication, private and public databases are also provided by CloudKit so the developers can focus on the client-side development and let iCloud handle the server-side logic. What’s even better? With some pretty high allowance on usage, all of these wonderful features come for free with Apples developer program. iOS8 is truly a milestone for iOS. With APIs mentioned above and new features like HealthKit, HomeKit and Handoff, the possibilities for what an app can do now is really endless.

Xcode and Swift: Good has just become better

Like many iOS developers, Xcode is one of my most often used applications on my Mac. I don’t always like Xcode. But I have to say, as the go-to iOS development tool, Apple is making Xcode a better tool each time a new version is released. Xcode 6 is no exception. Before we dive into Xcode, let’s talk about the Swift language first. I think Swift is the biggest surprise from Apple since the introduction of Macbook Air. There was absolutely no prediction that Apple was going to introduce a brand new language in this year’s WWDC keynote. Swift has really shocked the iOS developer community (in a good way, mostly) and you can tell that by looking at the expressions on the faces of developers attended the keynote. Given several advantages over Objective-C and ease to learn, Swift has become an instant hit among iOS developers and even potential developers who are trying to find a new language to learn. As the software quality company TIOBE pointed out, by the time they post the programming language popularity rank for July, Swift will probably be in the top 20. Swift is designed to be modern, safe and powerful. The modern character of Swift comes from the new features such as closures, tuples and generics. The syntax is easier to read and maintain than Objective-C and features like generics in Swift will also enables developers to do things they could never be able to do with Objective-C. Safety in Swift is ensured by eliminating classes of unsafe code and always initializing variables before use. Swift is also designed with the idea of being a powerful language in mind. It uses the high-performance LLVM compiler just like Objective-C and will be transformed into optimized native code to get the most out of Macs and iOS devices. With all that being said, Apple didn’t just released Swift as a single new language. All of Cocoa and Cocoa Touch as well as other libraries in iOS and OSX SDKs are updated to support Swift. And of course so it is with the latest Xcode 6.

Xcode 6 comes with many new features and some interface revamping. One of them is the Playground. Playground offers great ways to learn Swift, try new codes and develop custom views. The code is executed automatically and result appears immediately. Developers can see visualized results, imported resources, and created views in assistant editor. Several other features such as timeline slider are also available in the Playground to offer more functionalities.

Playgrounds are more just for trying out new stuff. When it comes for developing the interface, Apple now offers live rendering in the Interface Builder. Developers don’t have to build and run then switch between Xcode and simulators (or devices) to see the result of a custom view. In Xcode 6, the changes are automatically applied into your custom views in the Interface Builder. And for debugging the views, Apple has introduced the View Debugging feature which will turn the UI into a 3D rendering of each layer in the stack of views. Developing and debugging custom views has never been easier before. Speaking of Interface Builder, in addition to the newly introduced OSX Storyboard, Interface Builder now works with Size Classes. Instead of specifying Storyboards for different screen sizes and devices, developers now can use one Storyboard with Size Classes and Auto Layout for all screen sizes. And there is also the Preview mode to quickly check the interface without having to run the app. Last but definitely not the least, I want to talk a little bit about debugging. LLDB debugger became the foundation for debugging in Xcode 5. In Xcode 6, it has just become better with Swift REPL. Swift REPL, or Read-Eval-Print-Loop is an interactive version of Swift lives in the debugging console in Xcode or Terminal. Developers can use LLDB just as before but now it will also give debug information for Swift codes. It is also possible to validate existing code or even trying new codes right in LLDB with Swift REPL.

Epilogue

iOS8 and Xcode 6 has really opened more possibilities for both developers and Apple itself. iOS8 has laid the foundations for Apple to make more interesting new products such as iWatch and potentially some automated home control devices. Xcode’s new Storyboard with Size Classes also make it easier to develop apps for existing iPhones, iPads or even for the future iOS devices with larger screens. I believe when Apple releases their next generation devices and lifts the NDA on iOS8, the excellent iOS developer community will surprise the users with some pretty interesting apps we have never seen before. 2014 is going to be a good year for all iOS and OSX developers.

In Part One of this blog, we talked about the general idea of blocks and how to use them. We also discussed the concept of concurrency and two APIs in Objective-C for concurrency: Dispatch queues and operation queues. In this second part of the blog, we will dive deeper into concurrently executing blocks using NSBlockOperation objects. And finally, as promised in the first part, we will look at an example of a typical “gotcha” and show you how to avoid it when using blocks. Please still keep in mind that this blog is designed for readers with intermediate knowledges of Objective-C and we’re using Automatic Reference Counting when coding.

NSOperationQueue, NSOperation and NSBlockOperation

NSOperationQueue

As the name described, operation queues are queues of operations, specifically in Objective-C, they are NSOperationQueue and NSOperation objects. Have you noticed that both the queues and the operations are objects. That means we can use them just as any other Objective-C objects. NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init]; [operationQueue addOperationWithBlock:^{NSLog(@”A block in an operation queue”);}];

The two lines of codes above show how to initialize a NSOperationQueue object and add an operation to the queue using a block. You can also add NSOperation objects to the queue but we will talk about it later after we discuss more on NSOperation class. NSOperationQueue roughly follows a first-in-first-out policy when managing the operations and will make its own decision of when to start an operation.

NSOperation

Now it’s time for some NSOperations. NSOperation is an abstract class which means it requires subclassing in order to use it. Don’t worry. It’s not complicated. Below is the content of our SampleOperation’s header file. #import <Foundation/Foundation.h> @interface SampleOperation : NSOperation

@end

And the implementation.

#import "SampleOperation.h"

@implementation SampleOperation

– (void)main { @autoreleasepool { NSLog(@”I’m an operation”); }

}@end See? It can be as simple as overriding the “main” method in the concrete class you created, creating an “auto release pool” and putting your codes into it. Since the operation won’t be able to access the main thread’s auto release pool, you have to create your own for the operation. And yes, the syntax shown above is written under ARC environment.

There’re also two other important methods in NSOperation class. The “Start” and “Cancel” methods. You don’t usually override the “start” method and when you call the method of a method, the operation will begin to execute. When an operation is added to a queue, the queue will decide when to call the “start” method of the operation. The “cancel” method is used to cancel the operation. When you write your main method, you should frequently check if the operation is cancelled by checking “self.isCancelled”. Whenever the statement is true, you should stop the execution right away.

NSOperation + Blocks == NSBlockOperation

It seems like we haven’t talked about blocks for a long time. I know you miss them. And now, let’s combine our knowledge of NSOperation and blocks by looking at a concrete class of NSOperation provided in Objective-C, the NSBlockOperation class. A NSBlockOperation object can contain several blocks and concurrently execute the blocks just like an operation queue.

NSArray* blocksInOperation = [blockOperation executionBlocks]; // 3 The first line is the code to create a NSBlockOperation object. Line 2 uses the “addExecutionBlock” method to add another block to the operation. And the last line shows how we can get all blocks inside a NSBlockOperation object by calling the “executionBlocks” method. Please notice that the blocks added to a NSBlockOperation object should take noparameter and return no value. And since the NSBlockOperation is just a concrete subclass of NSOperation, we can still use the “start” method to kick off the execution.

Bonus: Canceling a NSBlockOperation

Congratulations! You’ve earned yourself a bonus chapter. In this part of the blog, we will combine our knowledge of blocks, NSOperation and NSBlockOperation by looking at an example of canceling a NSBlockOperation. As we discussed earlier, when overriding the “main” method of a NSOperation subclass, we should check if the operation is canceled as frequently as possible. That guideline also holds true for NSBlockOperations. That sounds pretty easy. You may think it should be just like the following codes.

What about this then? We said earlier in Part One that we can make variables mutable inside blocks by giving them a “__block” storage modifier. And we will get rid of the warning messages from Xcode if we modified our previous codes to the ones shown above. If we try to run the code, it will also work as expected. But… Have we really fixed everything? Let’s check the code from the fundamental stuff. “__block” variables will be retained for blocks to use them because it’s possible that the blocks are still running while the object containing the variables is already released. And how will the “__block” variables be retained? The block will keep a strong reference to them so that they won’t be released unless the block is released. From the NSBlockOperation’s perspective, NSBlockOperation relies on the blocks to perform its task. The last thing a NSBlockOperation object wants is to have the blocks released when they are still needed. Therefore, when you give the NSBlockOperation a block, the block will be copied into the object and the NSBlockOperation will keep a strong reference to the blocks it has. Have you smelled anything wrong with the codes we have yet? If you think it sounds like a memory issue, you are on the right track. Although ARC can dramatically simplify the memory management work for developers, it can’t do anything. Under ARC environment, a strong reference means increment by one to the reference count of the object. When the reference count becomes 0, the object will be released from the memory. In the codes we have, the block has a strong reference to the operation and the operation also has a strong reference to the block. This means the reference counts for the block and operation will never go to zero, which makes it impossible for either the operation or the block to be released from the memory. In Objective-C, this situation is called a “retain cycle”. Since the memory allocated for objects will never be deallocated, the retain cycle will cause memory leaks to the app. Well… What can we do to avoid the retain cycle then? Check out the codes below.

} }]; Let’s look at these codes line by line. First, we created a NSBlockOperation object. But this time, instead of using the “blockOperationWithBlock:” method, we used a pretty standard way to create the object by calling “alloc” and then “init” on the NSBlockOperation class. This is because we won’t be able to get a reference to the operation when using “blockOperationWithBlock:”. Then in the next line, we created another NSBlockOperation object but this time, we explicitly gave a “__weak” storage modifier to the new operation object and make it refer to the blockOperation object we created earlier. The magical word “__weak” will prevent the weakBlockOperation to have a owning relation with blockOperation and this will make sure no strong reference will be assigned between weakBlockOperation and blockOperation. Lastly, we added the block to the blockOperation. Be careful, in the block, we will check if the weakBlockOperation is cancelled not the blockOperation. Because the weakBlockOperation is assigned to the value (or rather memory contents) of the blockOperation, the value of their “cancel” properties should always be the same. This is the key to break the retain cycle. The blockOperation will still keep a strong reference to the block. But this time since the block is checking the weakBlockOperation’s “cancel” property, it won’t establish any strong reference to the blockOperation object. The retain cycle is broken. Without the retain cycle, the blockOperation will be released when its reference count is 0 and the block will be released with the blockOperation as it should. The weakBlockOperation is “weak” by its nature thus it will be released with no problem when it’s out of scope. We have solved this memory manage management issue.

Where To Go From Here?

In this part of the blog, we introduced NSOperationQueue, NSOperation and one of its concrete subclass, NSBlockOperation. We also solved a memory management problem in our bonus chapter by utilizing our knowledge of NSBlockOperation and blocks. Hopefully you can find some useful information from this blog. If you want to lean more about blocks and NSOperation, please refer to Apple’s guide on blocks programming and don’t forget there is alway the class reference for NSOperation.