Understanding Properties in Objective-C and iOS

I think one of the first questions all new iOS developers ask is “Why declare properties with attributes like (nonatomic, strong)?” This is especially true for those who learn iOS development through the Stanford Paul Hegarty iOS lectures.

Understanding properties in Objective-C and iOS can be tough the first go around. When I first started programming for iOS I didn’t really understand all the ins and outs of properties and I probably didn’t need to because I wasn’t writing complex applications.

Over the last 8 months I’ve done a fair amount of iOS programming and have run into a number of scenarios where I needed to create read-only properties and thread-safe objects/classes. Some times Stackoverflow.com just doesn’t cut it because there are so many different questions and accepted answers it’s hard to really tell when and why to code what. You always run the risk of just coding something that works, but not really understanding if it’s the best way or not. If you find yourself in this situation–wanting to better understand how to create a property with the right set of attributes (i.e. nonatomic vs atomic, etc.)–then the Programming for Objective-C guide for iOS is the right place to start.

I’d recommend against thinking you’re better off taking shortcuts by just digging around on Stackoverflow.com or random blog posts because reading documentation is boring and goes into unnecessary detail, especially if you want to grasp the fundamentals of when and why to code properties with specific attributes. The official documentation excels in this area because it provides the necessary level of detail with helpful examples. I’ve found it to be much more helpful in understanding the fundamentals of properties in iOS development. However, once you have read the documentation, the topics on Stackoverflow.com (and other sites) become much more meaningful and are very worthwhile.

Instead of paraphrasing the already concise documentation I’ll just summarize some of the key topics you can read about.** If you’ve been coding in Obj-C for a little while already I recommend jumping into the “Data Encapsulation” section of the Programming for Objective-C guide. This section discusses the following concepts:

  • Default property attributes (i.e. readwrite, strong, atomic)
  • When/Why to use property attributes with helpful examples
    • readwrite vs readonly
    • strong vs weak
    • atomic vs nonatomic
    • unsafe_unretained
    • copy
  • When/Why to use variable qualifiers
    • __strong vs __weak
    • __unsafe_unretained
  • Specifying getter and setter names that are different from property names (w/o implementing the method code)
  • Strong reference cycles and how to avoid them
  • Why/How you should “cache” weak variables

If you want further reading on variable qualifiers as it pertains to Automatic Reference Counting (ARC) then I recommend reading the Transitioning to ARC Release Notes. This documentation is quite insightful covers more on variable qualifiers in addition to two examples I found very helpful, namely an example of how the compiler interprets an implicit strong pointer to NSError and an example involving blocks and the __block qualifier.

**This begs the question “Why the blog post then if you aren’t feeding me any new information?” My goal is to provide a point of reference so that I and others will know where to look in the future. It’s not always easy to know where to look when there seems to be endless documentation on all possible subject matter. Furthermore, I’ve summarized the most important topics so I and others know whether that source will contain the information sought.

Forgotten Xcode Debugger Tricks

If you’re a pro iOS programmer, you may be a master at using the debugger. I, however, am not quite there yet.

I recently realized I’m very inefficient at debugging. So I decided to revisit Paul Hegarty’s lecture on the debugging. I’m glad I did because I relearned a couple tricks I had forgotten about debugging in Xcode.

Trick #1 – Immediately Break On All Thrown Exceptions

Instead of having all your uncaught exceptions get tossed up the stack to main, tell the debugger to break once they are thrown. This will help you debug your code much faster since you will know right where the exceptions are thrown in your code. To set this up, do the following:

  1. Go to the Breakpoint navigator in Navigators pane on the left (Cmd + 6)
  2. Click the little plus sign (+) button at the very bottom left
  3. Select “Add Exception Breakpoint…”
  4. Keep the defaults and click “Done”.
Xcode Debugger Break On All Exceptions

Trick #2 – Conditional Breakpoints

This is awesome for those methods that get called over and over again and you want to set a breakpoint to check the value of some variable (e.g. make sure it’s not equal to 0 or nil) but you don’t want your app to break…every…single…time. To enable conditional breakpoints follow these steps:

  1. Set a breakpoint
  2. Right click (or two finger tap) over the breakpoint
  3. Select “Edit breakpoint”
  4. Enter in a value (e.g. result == 0)
Xcode Debugger Conditional Breakpoint

Trick #3 – Access Variables Using the Debugger CLI

Sometimes it’s nice to see the value of a variable without hovering over it. From the debugger console, you can type something like print [self myVariable] to see the value of myVariable. However, this only shows the most information, like the value of the pointer (which if it’s 0x0 then it’s nil).

Another alternative is to do something like po [self myVariable], which basically calls the description method on the the object so it will print it’s description (“po” stands for “print object”). If myVariable is an array, you will see the contents of the array. This becomes quite useful if you get into the habit of coding description methods for your classes because then you can enter po self in the debugger and get all the information you need on the current instance of your class.

Conclusion

As you can imagine, there are a lot of other useful things you can do with simple modifications of these three tricks (i.e. adding actions to tricks 1 & 2, ignoring breaks on trick 2, exploring the other commands that can be used in the debugger CLI, etc.).

Lesson learned: Don’t be inefficient with your debugging. Explore the available tools.

iPad App Review: Notes Plus vs. Notability

Notes Plus App for iPadVS Notability App for iPad

Since I recently acquired an iPad 2 (last October-ish), I decided I wanted to use it to take notes in some of my classes, mostly in ECON 110. We graph supply and demand curves 90% of the time in that class. Taking notes on my computer wasn’t practical; I tried making graphs in PowerPoint. I also tried using the pre-installed Grapher app that comes with OS X Lion. Nothing was really working for me. Drawing with a track pad is very tiresome. So I went ahead an bought a stylus on eBay for about $7.00 and started researching apps. The two apps I ended up trying are Notes Plus and Notability.

(If you don’t want to read about my experience, just skip to the Epilogue: General Features & Screenshots)

Notability: An Impulse Purchase

I first purchased Notability because I saw it was “on sale” for a couple days and bought it for ~$1.99. I was very impressed with most of the functionality.

My greatest disappointment was adding figures and drawing. In order to draw with this app you have to insert a figure. In other words…

While all other functionality was more than satisfactory, I felt like I really needed an easier way to draw straight into my notes. So I spoke with a friend of mine who also has an iPad and who I had seen using it to take notes in some of my classes. He recommended Notes Plus.

Notes Plus: Referred by a Friend

So I give my friend a short demo of Notability and then let him try it out for himself. He seemed reasonably impressed and didn’t have anything really bad to say about it. Then he gave me a short demo of Notes Plus. It seemed pretty comparable. They had some different approaches to the same problem but both were well executed. However, what caught my eye most was that with Notes Plus you can draw straight into your notes. No extra, separate figures. AND it has great options for automatically detecting, smoothing and straightening lines and shapes. I bought it and downloaded it within the hour.

My first fuss with Notes Plus was that the drawing/note-taking space wasn’t big enough. I had to keep adding more pages to my economics notebook. However, that was just a dumb move on my part. There is actually an option for making the pages bigger. So I tried that for a while. It worked great.

My biggest beef came down to this: my hand writing is so sloppy even with a stylus that writing out notes on the iPad was messy and inefficient. Even with the gorgeous character smoothing, it just wasn’t enough. I would write and undo and rewrite and erase and…yeah. And as easy as adding textboxes is in Notes Plus, it just isn’t simple enough or hassle-free. It takes a lot of extra time to move the text boxes around and resize them. In the end, I was getting more and more behind in my notes and I never had time to really focus on what the professor was actually lecturing on. I spent all the time people were asking questions just catching up. Eventually, I decided I would just have to resort to the old graph paper notebook.

Conclusion

So it’s a sad story of how I fought the battle of traditional mediums vs. technology. But if tech just doesn’t do the trick, why bother? Why inconvenience yourself? Besides, my wife still uses the apps to draw, and I’ve found they are great for other things like entertaining children at church or visiting nephews. Though, I’ve found better drawing apps for that too…

Something worth noting about both apps is that they can sync your notes to Dropbox.

For all general purpose note-taking (when I don’t need to draw), I use Evernote or Simplenote because they sync to my existing accounts online where I store all my notes. What has been your experience with note-taking on the iPad? What works for you?

Epilogue: General Features & Screenshots

I’ve included the primary features (as described by the developers on the AppStore) for those of you potentially interested in either of these two apps.

Notes Plus

1. CLOSE-UP HANDWRITING
Hand write comfortably with your big finger, your text will show up as fine as with pen and paper. Auto-advance feature let you write even with your eyes closed. Advanced stroke smoothing algorithm makes your writing look as good as ever; the faster you write, the better it looks.

2. PALM HANDLING
Lay your palm comfortably down with Palm Pad.

3. TYPED TEXT MIXING
Let you insert keyboard text anywhere on the page with many type faces, font sizes, and colors.

4. SHAPE AUTO-DETECT
Let you draw a basic shape (ellipse, rectangle, line, polygon, …) with your finger, auto-detect and insert the perfect vector shape, then let you edit it.

5. VOICE RECORDING
Let you record audio while jotting down the note. Perfect for meetings, classes, or conferences. Recordings are linked with pages to provide easy playback.

6. EASY EDITING
Let you select handwriting text by just circling around it, then erase or re-arrange it. Erasing a writing is as easy as drawing a line over it. No awkward switching between erase tool, selection tool, and draw tool.

7. EASY ORGANIZING
Provide a complete folder structure. Private folders can be password-protected. A folder can have many notebooks; a notebook can have many pages. Pages are listing with thumbnails. Provide ability to move, copy, duplicate and delete notebooks or individual pages.

8. RECOVERING FROM YOUR MISTAKES
Full undo/redo support. Yes, it does have REDO function; touch and hold undo button to reveal the undo/redo action sheet. Also let you recover your deleted notebooks or pages.

9. CUSTOMIZING TO YOUR TASTE
Many options are provided including: stroke color, thickness, transparency; text font, size, color; paper background, etc.

10. (LAST AND MOST IMPORTANT) CLEAN & NATURAL USER INTERFACE
As you can see from the screenshots below, this app stands out for its clean interface. A great effort was put in to hide controls so that it would not cluster the interface. You should be able to start without a tutorial.

The developer encourages you to email him with any questions concerning features since he has only listed his “top 10.” It might be worth your time since he tries to respond to all emails within 24 hours.

Notability

** Full-featured Handwriting **
Amazingly smooth ink makes capturing ideas easy and awesome. Notability’s zoom window helps you quickly and clearly draw every detail and the palm rest protects your notes from unwanted marks. Our scissors let you copy, move and even re-style the color and width of any ink. Reordering notes is a joy: drag-and-drop thumbnails, while adding or removing pages as needed. Your notes should be as unique as you are, so choose a paper to fit your style and use a variety of pen colors and widths to create beautiful notes.

** PDF Annotation **
The same tools that help you take beautiful notes in Notability equip you to annotate PDFs: record, type or handwrite on anything. It’s easy to share your annotations with anyone using email or Dropbox and more.

** Advanced Word-Processing **
Notability’s features like styling, outlining, and spell check are the perfect tools to get the job done quickly and accurately. Other tools like bullets, bold, italic, underline, font presets, cursor controls, and more, seamlessly integrate to help you create rich notes.

** Linked Audio Recording **
Audio recordings automatically link to your notes, so go ahead and take notes with confidence. While reviewing your notes, just tap a word to hear what was said at that moment. Our advanced audio processing features create brilliant recordings in any setting. Use the recording feature to capture your own voice for memos, presentations, or speech practice.

** Auto-sync **
Work with confidence: with Notability’s auto-sync, your notes are always backed up in the cloud. Easily collaborate at work or school sharing ideas and notes on the fly.

** Media Insertion **
Enhance your notes by adding pictures from your photo library or from the iPad camera. Insert web clips, figures, and drawings to compliment your notes. Crop, resize, and draw on images to make them perfect. Your text will automatically flow around them.

** Library Organization **
Your ideas and notes are incredibly important to you, so Notability makes it simple to organize, protect and share this information. Drag and drop notes into a subject and use a password to keep notes secure. Auto-sync makes backing up simple: your notes are automatically uploaded to Dropbox, iDisk or WebDAV. Import notes, PDFs, and RTFs from the cloud or web. And share notes via Email, Dropbox, iTunes File Sharing, and AirPrint.

Screenshots

Notability - Mainscreen

Notability – Mainscreen

Notes Plus - Notebooks

Notes Plus – Notebooks 

Notability - Writing

Notability – Writing

Notes Plus - Writing

Notes Plus – Writing

Notability - Note Taking & Figures

Notability – Note Taking & Figures

Notes Plus - Drawing Figures

Notes Plus – Note Taking & Figures