Follow Me on Twitter!
2012
01.22

If you’re an iOS developer using Core Data in your app, whether a n00b or expert, you should be using Mogenerator. I mean, really, you *should* be using it. If you don’t, well don’t worry, I’m not only going to tell you why you need it, I’m including a tutorial on how to use it!

So let’s get to it!

I know Core Data already, so why do I need Mogen?

Core Data is a huge beast of a thing. There’s so much to know, and you’re not going to get any new functionality from Mogen either. What you *will* get, however, is a Core Data that will be far, far easier to use. This is what Mogen does for you:

  1. Faster and easier generation of concrete classes for your model.
  2. A proper two-class treatment in that generation.
  3. Alleviates the need to wrap numeric attributes in NSNumber objects.
  4. Handy setter methods for manipulating sets easily.
  5. Handy wrapper methods for insertion/entity identification.

I can’t wait to get into it all, but first you need to install Mogen and set up your project!

Installation

The first thing you’ll need to do is install Mogen. It’s simple, you install Mogen from a DMG. After this one-time step, we’ll now configure your project to use it:

  1. In your project, open your project properties and click “Add Target”.

  2. Add an “Aggregate” target (you’ll find it in the Other grouping). Hit Next.
  3. Name the target whatever you’d like. I’ll call mine Mogenerator. Hit Done.

  4. Now select the new target you just created and click “Add Build Phase” then “Add Run Script”.
  5. Open the Run Script group that just appeared and enter in the information as you see it below while adjusting the names to match your own project. Feel free to modify it to fit your own needs, perhaps to create your model files in a subdirectory.

Congratulations, your project is set up to use Mogen! There’s just one more thing you need to know: When you create entities in your data model, be sure to populate the “Class” field with the same name as the entity. (You can name it whatever you want, actually, but that would be mighty stupid to do.)



We’re all ready to go. What did we win?? I’ll outline that next.

Faster, Improved Class Generation

I’ve been programming iPhone apps for almost 3 years now and, I’ll be honest, I still can’t tell you the exact steps to generate Core Data classes. It seems to involve selecting the right entities in the model, adding a new file, and changing some checkbo — look, I don’t know. I think they made it a little easier recently, but it was crazy and I use Mogen now so I don’t care anymore. ;-) All I know is it’s much easier now.

Change your build target to “Mogenerator” (or whatever you called it) and hit ⌘B to build. And you’re done. At this point, since you generated new files, you’ll need to add them to your project. You won’t have to do this on future regenerations, but for new entities, yes.

You’ll notice that there are two sets of files, _Event.* and Event.*. If you’re not familiar with this pattern, it’s amazing. It’s also been used for years and shame on Apple that they don’t do this out of the box. The _Event.* files are generated and you should never touch them. The Event.* files are generated only if they don’t exist and you can feel free to add any methods and properties you like.

Yes, that’s right, gone are the days where you avoided adding methods to your concrete classes knowing that once you did you wouldn’t be able to generate them anymore. Add all you want, now! The clean coding gods will thank you!

From here on out, whenever you change your model, regenerate the classes, rinse and repeat.

Better Setters

Maybe I’m alone, but early on one of the mistakes I made over and over again was to forget that my numeric entity attributes were wrapped in NSNumber. I’d constantly write code like this:

if (user.isAdmin) {
    ...
}

WRONG! The isAdmin attribute is an NSNumber, so this will evaluate to true for all cases where isAdmin isn’t nil! I ran into this so many times I even contemplated scrapping Core Data to erase the emotional pain.

Not anymore with Mogen. You can now write the code as:

if (user.isAdminValue) {
    ...
}

This simple upgrade is a godsend! Setting attributes is equally easy, and you get to keep the original setters and getters to boot. You can use whatever is useful at the moment. With some attributes, I’ll use both versions:

Thank you, thank you Mogen!

Even More Useful Methods

Aside from the setters and getters, you get some useful methods for relationships, too. Now, I believe Apple has learned their lesson and now provide similar methods like these, but too little, too late. So, let’s say for example you have a entities named User and Role with a to-many relationship on User named roles. You can write code like this to add a role to the user:

User *user = [User insertInManagedObjectContext:moc];
user.name = @"John Blanco";

Role *role = [Role insertInManagedObjectContext:moc];
role.type = @"Administrator";

[user addRolesObject:role];

And you’re done. No need to create a mutable set or anything, it’s all handled for you. There’s a handful of other methods like this, one that lets you remove an object and two more that let you add or remove multiples objects in a set.

Validations, Too!

Mind you, this isn’t a Mogen thing. This is a Core Data thing. Validations let you test your data before saving to your persistant store. But, you might not even have known this existed! This is because you have to specify your validations in the concreate class and, if you’re not using Mogen, you’d have to keep rewriting them every time you regenerated your classes. WHAT?!

Now, you can specify validations like this:

- (BOOL)validateEmail:(id *)value error:(NSError **)error {
    if (self.email && ![self.email isValidEmailAddress] && error) {
        *error = [NSError errorWithDomain:@"MyErrorDomain" code:1];
        return NO;
    }

    return YES;
}

This is how you validate individual attributes, but there are other hooks available. Find out more about Core Data Validations to harness even more power.

Conclusion

I hope I’ve made my case for Mogenerator. It’s an invaluable tool! It simplifies anything and since I learned about it I haven’t worked on a project without it. Even better, since it’s a tool and not a library, it interoperates perfectly with other Core Data libraries like InnerBand’s Core Data Store and Magical Record.

Now go forth, young soldier!

  • Print
  • Facebook
  • Twitter
2012
01.21

Last October, I unofficially partnered up with Fish the Mouse Media and headed up the programming for Animal Alphabet HD, the interactive and kid-friendly alphabet app exclusively for iPad. After nearly 6 months of development (in mostly evening hours) interrupted only by the birth of my daughter in January 2011, the app was released to critical acclaim and glowing reviews.

Unfortunately, as goes the unpredictable world of the App Store, it didn’t equate to sales. It was tough watching it languish while my kids continued to play with it every day as they did while I developed it. When I’d finish an animal screen, I’d hand it off to my sons and say, “Hey guys, want to play with the Kookaburra?” They were the best beta testers and they still love it. Alas, being lost in the monstrous caverns of the App Store meant very few others got to enjoy it as well.

Then — A few weeks ago, while doing some pre-research for my own gaming project, I started tinkering with Animal Alphabet HD to see if I could squeeze it onto an iPhone screen. After a bit of success I got addicted and, in just a few days, an iPhone version was complete! Then, we not only released the update as a Universal app but we lowered the price to $0.99.

And that’s when we beat Cookie Doodle.

Ironically, on my daughter’s 1st birthday, the update arrived on the App Store (9 days ago now) and AAHD has steadily risen up the charts since. Today, it’s the #10 Top Paid iPad app in the Education category and still rising! It’s good to see the recognition for what I feel is an engaging, addictive, and most-of-all educational experience for kids! The Fish the Mouse team did an excellent job coordinating, designing and developing this game. Just the 3 of us.

I’ve written a couple dozen apps for the iOS platform. Many I developed on my own, others with teams. A few have hit high in the App Store, namely the MLS app (as a team via Double Encore) and Fuzz Alert Pro (independently for Fuzz Alert LLC). Animal Alphabet HD, though, is much closer to my heart. For all the work I’ve put in, it’s great to see it rewarded. It shows that despite all of us being underdogs when it comes to competing on the App Store, it makes the reward that much greater.

Let’s all keep pluggin’!

Note: In full disclosure, the Blanco family loves Cookie Doodle. :-)

  • Print
  • Facebook
  • Twitter
2012
01.17

iBoost is now InnerBand!

Just a quick announcement, to avoid naming conflicts with the mobile provider I’ve renamed iBoost to InnerBand. It’s hosted at its new InnerBand GitHub location.

  • Print
  • Facebook
  • Twitter
2011
11.07

For many iOS developers, layers are a lower-level, complex version of the UIView. In reality, it’s the UIView which is a thin layer on top of CALayer. Unfortuntely, 95% of the iOS books and documentation out there talk almost exclusively about the UIKit and so it’s no surprise we get that impression.

In this blog, I’m going to explain the difference between UIView and CALayer, tell you when you should be using either, and demonstrate the power of layers by creating a working clock.

UIView vs. CALayer

Despite what many developers think, it’s the CALayer that’s the fundamental drawing unit in iOS. The reason why we perceive UIView as such is because it’s a thin layer on top of CALayer and for most UI challenges using some form of UIView works just fine. You can create custom views, draw into them, handle user interactions, and even animate them without ever having to touch CALayer.

Every UIView comes packaged with a CALayer knows as the “backing layer” or “underlying layer.” Many of the methods you call on UIView simply delegate to the layer. When you change a view’s frame, it’s simply changing the layer’s frame. If you change the alpha, it changes the layer’s alpha…and so on with background colors, transformations and more. And while you can maintain a hierarchy of UIViews each representing parents and children of one another, you can do the same with CALayer.

Now, let’s say you wanted to write a Bar Chart component. You’d subclass UIView (or better yet, UIControl) and write the logic for displaying the colored bars you need to represent your data. If you’re comfortable with the UIKit, you might find it an easy choice to use subviews to represent each bar. You can use a plain UIView, slap a background color on it, size it…and repeat a dozen times depending on how much data you’re representing. But, you’d be wrong. You shouldn’t be using subviews, you should be using sublayers.

Should I use subviews or sublayers?

This isn’t a simple question, but there’s one rule of thumb that make deciding a lot easier. The main different between a view and a layer is that views can accept user input while a layer cannot. A layer is simply a graphical representation. Views can handle user taps, drags, pinches, etc. To me, this is all you need to know.

So, when making your bar chart, you should be using sublayers for the bars. Why? Because they don’t need user input and since they’re lighter weight than views, they’re the right choice. So what do you gain by using layers? Well, aside from performance, you also gain implicit animation and better control of the visual representation. You see, every property you change on a layer is automatically animated. You can disable them if you need to, but they come in handy. Also, you can apply shadow effects, corner radiuses, 3D transforms and more on layers. You can apply many of these on views, too, but they’re simply delegating to their “underlying layer” and in many cases stealing event notifications you’d rather they not from your view. :-)

Demo: Let’s build a working clock!

To demonstrate how we use layers, I’m going to build a working clock. The architecture will be as follows:

  • ClockView will extend UIControl so that we can use it with Interface Builder and, potentially in the future, handle user events.
  • All the parts of the clock will be layers.
  • Since all of the parts are layers, we won’t be implementing drawRect.
  • A timer, that we can start and stop, will handle updating the clock by adjusting the three hands.

Here’s what our clock looks like:

Every piece of it is rendered in layers: the face, numbers, ticks, all three hands, and the centerpoint. I used a mix of techniques to render it. Shadow effects give the hands depth, rounded line miters give the hands softness, and combining anchoring with transforms gives the hands a more natural clock look by having them rotate around the centerpoint. No PNGs were used and no primitives were drawn.

Here’s the source code. You can take this code and drop it right into your own project. Simply call ClockView#startUpdates to get things going! Also, note that I only implement initWithCoder, so if you want to add it to your UI programmatically, override initWithFrame as well. You’ll also need to link in the QuartzCore framework — anything that uses CA* will need it.

(NOTE: It’s not a memory leak, it’s ARC! Also, I recommend using constants instead of raw time constants. Why not try iBoost?)

On line #41, I use a CAShapeLayer. These things are awesome! By providing a path, you can make a layer of any shape. You can specify stroke and fill colors, change line attributes, and so on. The clock would be way more complex without these bad boys.

On line #45, I use the position property to place the face layer. Layers are positioned differently than views. While you might use frame, bounds, or center to position a view…you use bounds, position, and anchorPoint to position a layer. While bounds works as expected, position and anchorPoint are different. The anchorPoint is a CGPoint where the X and Y normally range between 0 and 1. The 0 represents the top or left of the image, and 1 is the bottom or right of the image. The default is 0.5, 0.5 which is the center of the image. That means that whatever you set the position property to, that’s where the center of the layer will be. You can change the anchorPoint to position things differently. If you set it to 0, 0, position will be where the top left of the image is. Get it? Additionally, you can make an anchor 0.5, 10 which will position the layer 10X the height of the layer above the position. Magic.

On line #59, I use a CATextLayer which lets you specify text easily as a layer.

On line #67, I use 3D transforms to position the numbers. By making the bounds of the number higher than expected, a simple rotational transform positions the numbers where I want. (If you wanted the numbers all “face up”, you’d have to position these using trigonometry instead, but this is a layer demo!) Note that the last 3 params of this method specify which axes to rotate around. I specify the last one, which is the z-axis, which is by far the most common.

Summary

Layers are the powerful core of the Cocoa Touch framework. Even if you’ve never used a layer directly, you’re probably familiar with many concepts because UIViews are simply thin layers on top of them. Want to give your view a rounded rectangle appearance? Simply set myView.layer.cornerRadius to 5.0! Want dynamic drop shadows to make image sizing easier? Set myView.layer.shadowOpacity greater than 0.0. DONE! Remember, UIViews are designed to handle user input, and layers are the graphical workhorse. Use them!

  • Print
  • Facebook
  • Twitter
2011
10.22

My experience as a technical consultant has taught me what the best projects to pursue are, how to smell a rat, and how to come up with the highest bid that wins. I don’t know, maybe I bid low, or too high, who knows, but I’ve got a great conversion rate on getting contracts signed so I’d like to think I’m doing a good job with it.

But why just share my insight with other developers? What about the other side of the coin? So, all you potential clients and entrepreneurs out there, here are some tips for getting the best fixed rate on a project from a consultant.

Introduce Yourself and Your Idea Well

I get a fair amount of email from prospective clients, that I’ve never worked with before, who’ve found me on Google. Sometimes they have a contract in mind, and other times it’s a partnership offer from some kid who thinks they can make a million-dollar flashlight app. For every email I get, I have to decide if I will potentially devote a handful of hours to phone calls, requirements gathering and ultimately a formal proposal. Every time I bark up the wrong tree, I lose a half-day or more of work time that will set me back on my current projects — so I have to choose wisely.

My advice if you’re looking for an iOS consultant is, when you write to that developer, take the time to introduce yourself, explain clearly what you’re looking for, and if you are company-backed — say so. This is important. When you tell me you are a manager at a company looking to build a project, you get instant credibility as a good lead. Is that unfair to independent venturists, yeah probably. That’s business, however, and if you have the advantage of a corporate backing then by all means flaunt it.

One of my best clients almost never was because I initially didn’t even respond to his first inquiry. Here’s the first message I ever got from him:

Hi -

I have an idea for an app I’d like to make what are our next steps?

- Some Guy I Never Heard Of

Ask yourself, how much time would you take from your work day to chase this lead down? I didn’t even bother. It took future emails and even then, when I had to cancel a chat due to the flu, I totally forgot about the person afterwards because in my mind it was likely never going to amount to anything. Boy was I wrong. But was it my fault? Hardly.

What he had failed to realize is that I get many messages that look like this from clients who aren’t looking to pay for work. In fact, the email is borderline spam. :-) Now, assuming that a developer does respond to this kind of message, you must remember that it really is true: first impressions matter. Over the course of correspondences, that developer will remember how things started and carry a shred of distrust. Perhaps a shard! So OK, with this particular client, I didn’t fully trust them until we first met some weeks later. Without trust, a developer may up their bid to cover the risk involved with that lack of trust and you may not even realize it.

It matters that much, yet only takes 5 minutes to write a solid opening correspondence. Put in the effort and it will be well worth it.

Know What You Want

This is a biggie. When a customer comes to me with a project in mind the first thing I do, of course, is ask about their idea (generally under NDA). Most customers have an idea, but a handful don’t. In many cases, that client is looking to me for guidance. (I am a consultant after all.)

But is that optimal? I can say that the more unsure the prospective client seems to be about what they want to build, the higher my bid will be. Why? Simple:

  • The more unsure a client is, the more change will be introduced later. The more change, the more net work.
  • It’s easy to envision that I’ll be spending many hours working with the client to nail down their requirements.
  • All of this produces risk that my bid will end up being too low. To be sure I don’t lose money on the deal, the bid must be increased to offset said risk.

I once had a client who I spent about 7 months with exchanging phone calls, emails, IM’s and what have you answering questions about what’s possible on iPad and working with them to formulate their requirements. I took calls on the road, while walking to the train, at work…everywhere. I even wrote a little demo app for them to show their own client. In total, I probably spent 12 hours of my time on all of this before any phase of the project had even begun. Clients like this do themselves a disservice because as a developer it’s easy to see huge warning flags in this behavior.

Contrast this with the clients I come across who have requirements, and even wireframes, in hand. These are the clients that clearly articulate what they want and they just need you to build it. I can confidently estimate the time needed to do it and am able to give a confident fixed price. Most importantly, that price is generally coming out lower than normal because I don’t feel pressured to charge for risk and perceived change. In addition, I don’t want to lose out to another consultant: I *want* this client.

My advice is to be these clients.

Be As Responsive As Possible

Finally, your developer is in butt-in-seat mode and product is being built. You’ve taken all the advice above to heart and have a solid deal signed and now you just have to wait for the work to be delivered. Alas, you’re not done! Fixed-bid contracts (as well as hourly) can crumble right underneath you if you hang the developer out to dry. It’s up to you to prevent that.

Let’s take a fixed-bid contract to start. Let’s say you agree to a $20,000 contract with the developer. With that, the developer has an understanding of the work needed to be done and the timeframe. Now let’s say that the project progresses and your developer is pinging you with questions and clarifications on what the app should do. If you aren’t responsive, the developer is liable to be (A) stuck or worse (B) continuing forward with an incorrect understanding.

You *have* to be responsible. No, responding within a day is not sufficient. Within an *hour* is. This might be inconvenient at times, but the quality of your app will suffer if you push the developer off. And it gets worse…if that developer is constantly having to wait a day or two to hear back from you, they will get irritated because it’s likely increasing their time expectations of the product and, if they are having to do rework, it’s increasing the expected work involved. What does this mean? It means the developer, in order to avoid losing money, will cut corners that will ultimately hurt you down the road.

Even worse, the developer will stop contacting you. That may make you happy, but realize that this means the developer is unsure of what to do but is uninterested in asking you. You’re going to get the wrong thing.

Is it fair? Actually, yes. If you don’t display the care for your app your developer expects, why should they care? A lazy customer suggests to me that they don’t expect the polish I was willing to put the extra effort into. It’s a natural human reaction that if you don’t care, I don’t care. This is best described by the Broken Window Theory and you should take the time to read it as it’s incredibly eye-opening.

So care. You’ll be rewarded. :-)

Conclusion

To get the lowest rate, and the best product possible, you don’t have to be worried about the above if you keep the following axioms in mind:

  • Be credible.
  • Be trustworthy.
  • Be dependable.

That’s it. I can’t speak for all developers but I’m sure I am when I say that we *love* customers like this. Not only will I give my most competitive bid for these customers, I’ll prioritize them above all others because I know I can rely on them and I want their business again in the future. And the bottom line is that if you’re the client, this is what you want your developer to think.

Now that we’ve got this understanding, let’s improve the relationships we have and get to work!

  • Print
  • Facebook
  • Twitter