How to Use Boolean Attributes in Core Data

Some Context

The data model of my current project started breaking after I versioned it to #7, rejecting my usage of Booleans. Part of my confusion was due to this selective, late-in-the-game breakage: booleans had been working fine up until now, and I hadn’t changed anything that I recall; #7 added a new transient attribute to a different entity. Shouldn’t they have been breaking from day 1?

I searched fruitlessly for “How to Use Boolean Attributes in Core Data” and variations on that theme, to no avail (excuse the redundancy).  Only after I had this explained to me in person did I realize that the answers were out there, obliquely (amongst the usual suspects: a Stack Overflow post, or this one, and in a few posts years old).

So you’ll forgive me if I broadcast and blast that phrase repeatedly, in the hopes of raising the SEO rankings for “How to Use Boolean Attributes in Core Data.” If you’re reading this, there’s a good chance you’re happy that I did. And if you’re unhappy, well, there are pills for that.


How to Use Boolean Attributes in Core Data


The Simple Way

  1. Check the “Use scalar properties for primitive data types” checkbox while auto-generating your subclasses.
  2. Grab a beer.

    "Use scalar properties for primitive values" checkbox
    The third screen in the process.

The Objective Way

  1. Instead of  YES and  NO , use  @YES  and   @NO .
  2. For control flow purposes (i.e., logical tests), call the  boolValue .



“The opposite of a fact is falsehood, but the opposite of one profound truth may very well be another profound truth.” –Niels Bohr

Do all AIBOs go to robot heaven? Do androids dream of electric sheep? Can Core Data keep track of profound truths? Yes, yes, and yes.

The limitation of scalars is that they must be, or not be, without question: 0/1, YES/NO. But opposite of ‘existence’ is not ‘death’ or ‘sadness’ or any something — it is non-existence.

In Objective-C, what indicates non-existence?  nil. If you need your attribute to have this capability, you need objects, such as NSNumber (ty CH for pointing this out).

Conversely, if you get errors with your boolean (see below), check to see if they are not actually NSNumbers. Two Things to be aware of then:

Thing #1: Setting the Entity’s value – You have added a boolean attribute to your entity in the data model, and had Xcode generate your model classes from it. You might think to code something like so:

You will probably get a warning along the lines of “makes pointer from integer without a cast.” This is because, as mentioned above, Core Data defaults to avoid booleans and other scalars, and so the attribute is stored as an NSNumber. Check your managed object header file (iOS 9: +coreDataProperties header), and you’ll see:

So instead, set the NSNumber like so:

Thing #2: Accessing the Entity’s value – In control flow statements, or wherever you are testing for the logical value of your boolean, you must always use the boolValue, because while  NO is ‘zip, zilch, 0’,  @NO evaluates to true (it exists)!

Instead, use boolValue:

Good hunting, peoples.


Solutions: Making a Calculator (Adding Buttons to Numpad)

Adding Buttons to UIKit’s Numpad

Screen Shot 2015-08-20 at 10.49.21 AM
Xcode Statistician from the Scrivener team at Literature and Latte

On a current project, users need to enter their locations by latitude andlongitude. True, the real world use of such a feature is dubious (do you know, right now, your latitude and longitude to four digits? Or the lat/lng of your destination? Yes? Well, my response to you, dear reader, is STOP DRIVING while reading blogs!). However, to make a simple calculator — or even more basically, to enter a number and then Return — you will need more than the UIKit-provided numpad.


You want to make a vanilla calculator. You would like to enter numbers to a UITextField without the default alphanumeric keypad, but rather with a number pad. However, the UIKeyboardTypeNumberPad was “designed for PIN entry,” and just contains the digits.


Add a custom UIToolbar on top of the default Numpad with the button(s) you require.

How It Works

(This solution is but One of Many.)

UIToolbar, which normally appears at the bottom of the screen, can be added to the inputAccessoryView belonging to the UITextField in question. After wiring up the storyboard, we will: (more…)

Open-Source UI Controls

Cocoa Controls on Your Device

Cocoa Controls: UI Elements for Hire

Perhaps the most powerful characteristic of knowledge is that it is relatively cheap (more specifically, it has a radically low marginal cost). Combine that with an open-source culture, and the result is that many wheels needn’t be reinvented. This is a heaven-sent boon for new developers, especially in the realm of UI and UX. As much as raster and vector graphics are on my list of mountains to conquer — and the principles of good design that make those packages useful — between Photoshop and UIKit, which do you think a babydev will prioritize? For many a beginner, this should be one less problem to deal with.

One very helpful site collecting various UI elements — with both free and paid code available — is Cocoa Controls. Give it a look over, and go nuts.

Do it one better: see the elements in action

For all that this website is an excellent resource, it is often hard to get a sense of how the elements work in action. Sometimes there are demo videos, more often flip-book gifs, but most often just static pictures. It’s also hard to get a ‘feel’ for the control in question. Although they are not so numerous, there are a few apps that help with this.

  1. Cocoa Stars – (Free), I cannot recommend this enough. You could get lost in the over 200 various controls on offer (mostly found on
    Cocoa Stars lets you test drive various UI elements right on your device.

    Github). While it certainly is not the end-all and be-all, it drastically lowers the barrier to entry, saving lots of time by letting you try out the controls on your device.

  2. NucliOS by Infragistics (free trial, copyrighted). This is a professional grade set of UI controls, with a professional grade price tag (starting at $899) – yet they provide their source code for you to peruse or copy, as a trial version. At the very least, it is a source of inspiration. [thanks to Omar Elfanek for discovering this]
  3. Dev Controls – (‘Free’ with copious ads and popups, grrr…). This app provides a curated list pointing to many UI Controls. Helpful, but not nearly as awesome as Cocoa Stars, which runs the controls it advertises. Still, this has over 1,000 elements to look through, and is a resource I am glad to have. And if the dev is truly spending time curating the list, then I forgive him the ads which support the endeavor.
  4. UI Tuner – (Free) – The iTunes description says it best:
      “This is a developers tool for designing, visualizing, and tweaking UI controls. Quickly change opacity, shadow orientation, transform parameters, just about any other visual property and see the result immediately on your iOS device. When you have your control tweaked just the way you want it, the app can email the source code to your Xcode system.” ++
  5. Cocoapods – (App Store link here [Free]). This is a helpful Cocoapods browser, but it doesn’t strictly run the pods’ demos on your device.

So all you new and experienced developers out there, you don’t have to reinvent the UIWheel! (You heard it here first 😉 )

 UPDATE (19 Aug 2015)

Also check out Libraries for Developers, another demo app like Cocoa Stars. (updated link can be found here).

Regular Expressions Can Solve Both Your Problems

In this post, we will:

  • Discuss/praise Regular Expressions in a cursory manner, but with enough quality links to get you started.
  • Provide an example of the power of RegEx (to validate a phone number).
  • Mini-Tutorial: Write a category on NSString to check if a string is a phone number, using NSRegularExpressions {iOS 8, Objective-C}.
  • Share jokes about regular expressions. Then we will laugh.

1. RegEx is a Powerful Tool worth adding to your Toolkit.

Others have defended the worth of RegEx used in moderation, so I won’t weigh down the internet by duplicating the substance of their arguments. This post aims to be first and foremost a tip-of-the-iceberg tutorial (feel free to skip to item #3). So although I will take it on faith that RegEx is a powerful tool, I feel compelled to make some semblance of a case for their newbie-friendliness. To wit, the unofficial bible of Regex’s  is Amazon’s #1 Best-seller!…in “FORTRAN Programming”. So let’s help the elephant exit the room, shall we?

Auchtung Elephants

There is a classic programming bon mot that goes like so:

Some people, when confronted with a problem, think:
“I know, I’ll use regular expressions.” Now they have two problems.

The reason for the knowing (nods|chuckles) from many of you in the audience is because, in the course of your career, you have encountered humor used to bleed off ‘regex anxiety’ (see the xkcd riffs here and here — no, really, come back when you’re done, I’ll wait), or else been force to scan such gems of brevity as this PERL-snippet of wisdom:

According to the poster of this string, this simply means to match any day of the year. It gets (irony alert!) a bit complex when you want to match that day by month, accounting for all the variations in month-length, adjusting for leap-years, and possible syntax variations like putting a space vs. a hyphen between significant figures. If you’re still with me, take heart: a regex doesn’t get much worse than that, so the hard part is over. Now the easy part.

(By the by, the guy who wrote the book on Regular Expressions [linked above], Jeffrey Friedl, did his darndest to trace that witticism; I betray my [pretensions to an] academic background by providing the link to that grand effort at proper attribution here.)

2. The Essence of RegEx in 10 Words:

RegEx is concise way of embedding logic into a search string. I’ll say it again: RegEx is concise way of embedding logic into a search string. That’s it.

RegEx is concise way of embedding logic into a search string. That’s it.

2 ex.

You are searching a (string →) data collection for the word ‘iambic’. But sometimes that word is at the beginning of a sentence. So you will accept both iambic  and Iambic .  Your logic may look like

Not too onerous. But what about checking if a string is a valid member of a class, say, a username? You have a number of rules for your username:

  • It can be any lower case letter, number, underscore, or dash…
  • …between 3 and 16 characters in length.

You could write out this:

Or you could use a regular expression like this (using the Regexer cocoapod):


3. Where To Get Started (Resources)

For ‘Structured Environment’ Learners:

  • A brand new CodeSchool intro course on RegExs, here (probably an hour or so of video, punctuated with interactive exercises called ‘challenges’; they’ve got a sense of humor, ++).
    • They also have a Ruby-centric screencast here.
  • Codecademy (not ‘Code Academy’, mind) has a JavaScript specific set of 10 exercises to get you up to speed, here.

For Unstructured Learners, there are many interactive tutorials (etc., etc.), walkthroughs, and playgrounds, books and graphic organizers (such as the following:


3a. Jokes

I love this list, with such gems as:

  • Some people, when faced with a problem, think, “I know, I’ll use #binary.” Now they have 10 problems.
  • Some people see a problem and think “I know, I’ll use #Java!” Now they have a ProblemFactory.

and a personal favorite…

  • Some people, wanting an escape from their full-time job, think “I know, I’ll contribute to open source.” Now they have two full-time jobs.

Please feel free to add links and original contributions in the comments.