[How to] Revert to a Previous Commit Made in Xcode using Git
NOTE: Make a copy of the project file you will be restoring before attempting to restore your work
When you create a new XCode project, you have the option of creating a Git Repository for the project. If you do, Git XCOde will create a Got Repositiry on your local machine for you to use with the project. To commit your work to the reposititory, got to File, Source Control, Commit.
Let us say that you committed your work a few days ago and as you were working on a feature, you messed up all of your code. You realize (a little too late) that you should have created a new branch and added your feature there, but you forgot and started coding away happily until now.
Here are the steps to get back a version of your code from a previous commit.
Go into XCode -> Organizer -> Repositories -> Your App, and find the name of the commit you want to restore.
This is the name that XCode assigns your commit, and the number we will use to restore it later.
Open up Terminal, go to the folder with the XCode project in it.
(Note, if you don’t know how to use terminal, learn it. It is super easy and is really powerful. Basically typing cd then the name of a directory will take you to that directory)
In my case, “cd Users/gazelle/Desktop/Kiva2″
Once you are there, type in “gitk” and hit return.
This will open up an ugly application that allows you to go through your previous changes with each Commit you made.
Click on the Commit number you want to restore (the same number used in XCode), and an SHA1 id number will appear. Copy this number.
Go back into terminal and type
“git reset –hard ce5bc9dc8c184f6f85159959564a1f112e32578″
Hit return and if you got no error message, you’re done!
Open up the XCode project from the XCode project folder, and your code should be restored to that earlier commit.
Happy coding!
UX Critique of Flipboard
Yesterday, Flipboard, an innovative newsreader, launched for the iPhone. The Flipboard iPad application has been out for over a year now, and is now on nearly one in every 10 iPads. Pretty impressive.
What makes Flipboard so popular is the UX (User Experience) design of the application. Simply put, it is a beautiful new way to use your iPhone, and everything you ever might need is 2-3 taps/swipes away.
When you first open the app, the home screen has 3 stories, the biggest of which contains a picture of the Flipboard application, with a smiling child in it. It has been proven time and time again that using smiling people on homepages or splash screens is a way to increase engagement, and Flipboard does that very nicely here.

Also note Flipboard’s huge photos. Each page of your news feeds has a nicely sized photo with just a few words of text on the top left. It is visually pleasing and functional.
One of the coolest features, from a UX perspective, is the animation of flipping the screen to the next one. As UX designers, we create interfaces that users will find intuitive and understand without any explanation. When you go from screen to screen, the current screen folds in half and flips, and the next screen simultaneously flips onto the screen. What separates exceptional UX interfaces from average ones is how the user can do what they need to. If they can touch an app and use it without feeling like they are actually using it, the UX is good. Most of the time, Apples standard animations get the job done, but not always. In this case, Flipboards new flip animation not only looks awesome, but makes the application easier to use.
How to convert Time NSStrings into seconds (iPhone)
When downloading times for audio clips using JSON or XML, take into account that the actual string might be a different number of components depending on the size. Some are shorter (“45:10″) and some are longer (“1:23:11″). Set the slider maximum value property to that of the length of the audio clip.
Here is the method that I used to convert from times to seconds:
- (NSNumber *)secondsForTimeString:(NSString *)string {NSArray *components = [string componentsSeparatedByString:@":"];NSInteger hours = [[components objectAtIndex:0] integerValue];NSInteger minutes = [[components objectAtIndex:1] integerValue];NSInteger seconds = [[components objectAtIndex:2] integerValue];return [NSNumber numberWithInteger:(hours * 60 * 60) + (minutes * 60) + seconds];}
Make the number of compnents 2 for times with only minutes and seconds, and 3 for times with hours, minutes, and seconds.
The Correct Way to Allow Users to Login to Facebook With Your App
When I’m trying a new app, I get annoyed when I am greeted with a Facebook signup page that requires me to type in my Facebook username and password. It is an extra step that takes 15 seconds of my life and can easily be avoided had the developer decided to open the Facebook app instead, and have me touch “Allow.”
It is the little things that makes some apps much better than others.
Replace this:
With this:
Harvard Tech Meetup (November 2011)

Yesterday was the Harvard tech meetup at the Burden Auditorium at Harvard University. The event started with some networking over food and went into a few startups demoing their products. 800 people had registered for the event, and while about 450 showed up, it was still a massive crowd of like minded entrepreneurs/designers/business students. I had never experienced something like this before. Thus far I have been programming away in a little bubble in Hartford Ct (where there is no start-up scene whatsoever), and this was my first exposure to the startup/developer community. I met some really creative people who are tackling real life problems with their startups, which really grounded me in this field. What these people are doing with their startups is exactly what I want to be doing as well. I definitely plan to attend each month, and possibly demo my own application in the next meetup.
The Startups:
Custom Made
Custommade.com is a website where people can get custom stuff made by local craftspeople. Take picture of a piece of jewelry or a table, and local craftspeople will bid on your project. They believe custom is a service, not a product, and that they sell you the story of the product with the product, not something made by a machine.
Skillshare
Skillshare lets you take classes taught locally by professionals. The idea is that you create a curriculum based on what you want to learn and meet people with similar interests.
Bon-App
Bon-App lets you see what is really in your food, and compare foods based on where they come from. You can find out that a bass from freshwater has 32 grams of protein per serving while a bass fed processed food only has 16.
EventPlease
EventPlease.com is solving the problem of “what is going on tonight?” This web application lets users organize and post events. You can track events, add them to your calendars, and share them. They aim to make college campuses more open.
Appbrick
EBooks on steroids. Appbrick allows book publishers and writers to write books on digital platforms
The Eatery
One of the most impressive apps of the event was Eatery, by Massive Health. They aim to use technology to stop chronic disease. I felt that they were trying to really help people get healthy, and they were passionate about both techonolgoy and health. The Eatery is one of the best designed applications I have come accross in a long time, and it really works. In one week, they had 1 million food ratings. 1 million!
Balbus speech
An iPad application called Speech 4 Good that helps speech therapy patients keep in touch and share progress with their speech therapists. It was demoed by the founder and CEO, Jack Mcdermott, who founded the company as a high school student while undergoing speech therapy himself.
Tivli
The most impressive app of the night was Tivli, which allows you to watch cable TV on your computer. No more cablebox, tv, remote, dvr, etc. Login from anywhere with your account and automatically stream content directly to your computer.
Thoughts on Apple Cards App User Experience
Yesterday I used the Apple Cards application to send a card to my family. What I love about Apple applications and try to do with my own apps is to keep everything streamlined and as simple as possible. Cards does an excellent job of taking one through the seemingly long task of developing a card and mailing it while making one feel like they are playing a game rather than doing an annoying task.
When you open the application you are greeted with the choose cards screen. Upon startup, the application knows you don’t have a card created, so it takes you right to the screen where you can choose a new card template.
The background is pretty dark, contrasting with the cards which all have white frames. This design choice makes the cards pop out of the page. Also notice the subtle reflection of every card directly below it that makes it look like the cards are standing. The application features a navigation bar, with only 1 button for saved cards on the left. While the user is holding the phone in landscape mode (the application only runs in landscape mode) this button is easily reachable with the left thumb. The user swipes left and right to sample all the cards and can see pretty much all the cards in a matter of seconds. There are also some icons on the bottom that the user can touch to get to a specific section.
Another way Apple could have designed this app is to have a tableView with the categories, and touching a row takes you to the cards in that category.
Apple chose to use icons instead of words, which I generally am more of a fan of. The users time is precious, and every second they spend in your app should be a useful one. Why make the user read a whole table of categories when you can insert easily discernible icon that can be understood at a glance? These small decisions influence how people interact with the app, and in turn, make the app better.

Once you select a card, the card itself lifts from the selection screen and through some very nice animations, it flies to the next screen, where it falls onto the envelope. The animations do an excellent job of making you feel like you are actually making a card, and not interacting with a device. This is one specific area where Apple has shined and other platforms have not, in being able to detach the user from the technology and connect directly to their content.
One of my favorite things about the application is how simple it is to do all the tasks that one needs to do. Let us make a quick list of them.
- Choose a picture for the back and crop/fix it
- Write a message on the inside of the card
- Choose fonts and sizes for the text
- Write the address of the recipient
- Write the address of the sender (you)
- Pay for the card
For the three main parts of the card (The outside, the inside, and the envelope) there is a UISegmented Control on the top of the screen with each one of those places. From any of the card views, you can get to any of the other card views, with just one tap. There is no “save” button either, everything saves automatically.
For the outside, you can either tap on the picture to select a picture, or the text to edit the text.
Tapping on the empty picture on the card takes you to the picture selection screen, where you can choose from the library or take a photo. Choosing a photo and selecting it only takes 4 taps. (Something I do when creating a UI design for apps is to see how many taps the user must do to complete a task. Generally speaking, the less the better, and I usually create multiple User Interfaces for each app and test it on random people to see how many taps they do to complete the task).
When you tap on the text on the card, you are immediately taken the to the text, highlighted, with the keyboard on screen. You don’t have to backspace all the text then put your own in, you just type and it instantly goes on the card. Other apps will take you to a different modal screen with a text box, and whatever you type will go the card in the next screen, but Apple does it right. What you type you instantly see on the card. Less taps, less screens, less effort needed by the user.
The Inside of the card is the same idea. When you go from outside to inside, the card actually flips open.
There is only one thing you can do here, tap the text, and you can change it. That is it. But where are the fonts? And where are the colors? Why can’t I change to text color? Because you don’t need to. Apple took the headache away from you by including one, matching color scheme per card. Contrary to what one might think, less choices = happier user.
When you tap envelope, the card slides to the right, and the envelope comes out in front.
Here you have the option of selecting people from your address book, which makes choosing the recipient take just under 4 taps. The same goes for the sender. You also have the option of manually typing them yourself, by simple tapping on the area. The font and color of the text is chosen for you.
Once you are done, you tap the $2.99 button on the top right (the button is in blue to differentiate it from the other buttons. It makes it very clear this is the goal. Psychologically the user is enticed to touch it because it is lit up). The application asks you for your appleID password, and that is it. The card goes into the sent cards screen.
Let us review all the tasks we needed to do to make the card and see how many taps we needed
- Choose a picture for the back and crop/fix it (5 taps max)
- Write a message on the inside of the card (2 Taps + text)
- Choose fonts and sizes for the text (None)
- Write the address of the recipient (2 Taps + text)
- Write the address of the sender (2 Taps + text)
- Pay for the card (2 Taps + password)
The application makes it incredibly easy to create a card in less than 2 minutes, and offers transitions between the screens to make the act of creating a card feel realistic and fun. I have always admired the Apple apps for their simplicity and their intuitiveness, and I always strive to do the same for my apps.
Thoughts Apple’s iPhone Mail App User Experience
While reading Apple’s Human Interface Guidelines, I came across the discussion of the iPhone mail app.
What intrigued me was the following section:
Distinct, highly focused screens. Each screen displays one aspect of the Mail experience: account list, mailbox list, message list, message view, and composition view. Within a screen, people scroll to see the entire contents.

Easy, predictable navigation. Making one tap per screen, people drill down from the general (the list of accounts) to the specific (a message). Each screen displays a title that shows people where they are, and a back button that makes it easy for them to retrace their steps.
Simple, tappable controls, available when needed. Because composing a message and checking for new email are primary actions people might want to take in any context, Mail on iPhone makes them accessible in multiple screens. When people are viewing a message, functions such as reply, move, and trash are available because they act upon a message.

Different types of feedback for different tasks. When people delete a message, it animates into the trash icon. When people send a message, they can see its progress; when the send finishes, they can hear a distinctive sound. By looking at the subtle text in the message list toolbar, people can see at a glance when their mailbox was last updated.
It is very important to include feedback to your users when they do something with your app. I went back and played with the mail app and noticed that everything you do creates a certain kind of feedback to let you know what you meant to do is actually happening. It feels like you are playing a game rather than doing something otherwise really boring, checking your email.
As in the mail app, feedback can be a sound, an animation, a progress bar, or even an indicator view. While developing your applications, make sure to include a step towards the end that properly gives the user feedback depending on what they choose.
Why The Best iPhone Utility Apps Do One Thing Well
The best apps are those that benefit not just the organization, but the user, and to truly benefit the user, one must create a simple app that does the task at hand quickly. Here is why.
People that use iPhones are people with busy lives. The iPhone is a device that is used in bite sized chunks of time, like on a subway ride, while waiting in a doctors office, waiting for laundry to finish, while in a boring meeting, or even while driving. Some people assume that the iPhone is a device people spend hours on at a time, and that may be true, but bever in just one application. Apps usually are opened and closed several times in the same minute.
They say the average app gets deleted from the users iPhone in just under 11 days afer being downloaded. Apps that stay on home screens more than that period are usually apps that provide some serious benefit to the user, quickly. The key here is speed..how fast can you provide your user with what they need before they feel the urge to hit the home button?
Let us take an example from one of my favorite apps, Shazam. Shazam is an app that solves the problem of “What is that song?” Many times I’ll hear a song outside and I’ll wonder what that song is. The solution is Shazam, which uses algorithms to listen to whatever song is playing and find it for you. Shazam is awesome because it is super simple. Here is the first screen that comes up when you open the app:
What you see is a huge button, and a “Touch to Shazam” command. This button cannot be missed because it is bigger than anything else on the screen, and the fact that it is round makes it very clear it is a button. When you tap the app, you get to tag your song, exactly what you wanted. It is true that Shazam does other things as well, like let you discover new music, but the focus of the app is on the one problem that users will have, What is that song? Of course, you don’t have to do anything after you hit the button, it listens and shows you the song on the screen. Simple, useful, easy, fast.
Another app that does this well is Google Translate. Users that open the app will most likely want to translate something into another language.
The to and from languages are the first things the user sees and right under it is the text input area. That is really all the app can do in terms of help you translate something. It can save your recent history, and allows you to star some trnaslations you have made, but the most important tasks is the first one the user sees. Google got this right when they created the following different apps: Google Search, Google Plus, Google Earth, Google Translate, Google Books, Google Places, Google Shopper, Google Latitude, etc. All different, highly specific and fast apps that do one thing well.
An app that does a poor example of this is the The Weather Channel app, contrasted with Apple’s Weather app below.
Someone who opens up a weather app is most likely interested in finding out what the weather is like where they are, and what it will be in the next few days. Apple’s Weather app has all that one would need to know about the weather for the upcoming week in one screen. It shows you if it will be sunny/rainy/snowy with a huge picture, the highs and lows of the day, and if you touch a day, even the hourly expected temperature. It is one page, with the current temperature in a huge hard to miss font and an info button that enables you to switch the city.
The Weather Channel App is a completely different story. First of all, there is a huge ad on the top of the screen, which is super distracting. The ad is not centered, as you can see some of the background color around the add, and contains an unreadable logo in its bottom right corner. This just bothers me. Below this is a search bar followed by 2 buttons, a pinpoint location button, and a bookmark button. Every element or button that added on the screen is an extra thing the user needs to look at and decide whether or not to touch in his mind. Instead of a button, Apple uses the paging technique to solve the bookmarks issue, which is a much more intuitive and cleaner solution.
What amazes me is what comes next. There is a twitter button, a button with 2 unequal sized arrows, followed by a small Weather Channel logo. None of these design decisions make sense to me. Who would want to tweet the weather? It doesn’t seem like the average user will need to, let alone ever want to tweet the weather. And what does the two arrows buttom mean? This button is not a good choice to use as it is very unintuitive and doesn’t let the user know what it does by looking at it. The logo is also in a wierd place. (On the second toolbar to the right?)
The area under this has the actual weather, with a clear sun to represent sunny and the temperature in a neon yellow like color. To the right is a lot of information that the average user will never care about. UV index? Dew point? What do those even mean? The Tab Bar on the bottom of the screen is also confusing. It has 8 tabs, and it is scrollable, which is not something we are supposed to do as developers. We create iPhone like interfaces for our apps, because people expect their iPhone to behave in a certain way. People expect their tab bar to have 5 tabs, and if there are more, then have the last tab as the more tab. In their attempt to include as much information in the app as possible, they confuse me. I’m scared to touch any other tab.
There is too much information on the screen. Now this app may in fact be for the weather enthusiast and not for the average iPhone user, it , but as the main Weather Channel app, it should be simpler. Perhaps they should have developed a simpler app for everyone and an advanced one for others.
[HOW TO] Use Color from RGB on iOS Applications
I do all my design work in Adobe Photoshop, and changing an iOS application’s colors using the initWithRed:green:blue method is really annoying way to traisition from Adobe’s color system to iOS.
[[UIColor alloc] initWithRed:60.0 / 255 green:70 / 255 blue:15 / 255 alpha:1.0]
Here is a way to use colors from RGB
Go into the application.pch file and type in the following code:
#define UIColorFromRGB(rgbValue) [UIColor \colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]//usageUIColor color = UIColorFromRGB(0xF7F7F7);
Then go to wherever you want to use the color, and use the UIColorFromRGB method and insert the Photoshop color.
iPhone Application UI Design, Design, and the Programmer, and Why They All Need Each Other
In order for an iOS application to be created, ideally you would need 3 different people, a UI (user interface) designer, an iOS designer, and an iOS developer. I would argue that no one of these is more important than the other.
Before any coding takes place, there must be a User Interface designer who mocks up the screens of the application. This is usually done in greyscale, either on paper or in Adobe Illustrator, and is called wife framing. The intent here is to visualize the flow of the screens, the placement of the main features and information of the application, and to make sure it is intuitive and simple. There are hundreds of different ways to create the same exact application, and it is the UI designers’s job to make sure the app behaves the way it is supposed to. This means ensuring the application’s information is clear and easily found by the user, making sure all buttons are placed in intuitive locations, and more importantly, that the application feels right.
For wire framing, I use the iPhone UIStensil and their letter iPhone template.
Here is an example if what wire framing looks like from one of my own applications.
To illustrate the different approaches one can take designing the user intercace of an application, here are 2 news apps, the Huffington Post on the left and the NY times on the right. While they are both essentially news apps, with a similar look, the applications are very different from a UI perspective.
First of all, the Huffington Post news article cells have the title of the article in Helvetica, and a photo, and that is it. The entire article cell is a picture relavent to the article, and the title. The UI designers behind this application decided that this is all they would need to put to get the summary of the article to the user and have them touch the cell to read more. The NY-Times application takes an entirely different approach. The NY-Times app has the title in a Times New Roman like font, with no photo, and has a small 3-4 line blurb about the article underneath. This gives off the impression that this application is for someone who is a little more serious about their news. Also, the Huffington Post application has a plus on the right side of the cell that, strangely, bring up a popover with the latest current news that is similar/relevant to the title of the article. The NY-Times app does not.
Also, take a look at the tab bar. The Huffington Post application has 5 different tabs, and uses the generic iPhone tab bar. (Standard size, blue selected item). It has Front Page, Sections, Search, Favorites, and Settings. The NY-Times app on the other hand has a bigger, custom tab bar with only 4 tabs, Top News, Most Emailed, Favorites, and Sections. The NY-Times app essentially took the settings tab of the Huffington Post app and placed it on the top right corner of the navigation bar. The UI designers for the NY-Times application made this decision counciously because they want the tabs to be all news- and nothing else. They also have Most Emailed as a tab, giving it equal importance to the top news and favorites. I suspect this is due to the traffic they recieve from those specific news articles.
I do not mean to say that the NY-Times application is necessarily better than the Huffington Post application. It is true that the NY-Times application has a slightly more mature design, but these applications are meant for completely different audiences. The Huffington Post audience is younger, and wants information as fast as possible. I look at it once a day and mostly just skim the headlines to see if anything interesting happened. I am not interested in reading long, lengthy, highly thought out opinion pieces like the average NY-Times reader does. Each application needs to be wire framed based on the user who will experience it, and optimized for them.
Once the UI design is complete, and the team agrees on the currect interface, the designer then takes on the actual design. Good app design is not only about good looks, but it also influences how to user interacts with the app and how they use it. How is the icon going to look? Is the background going to be noisy or have a gradient? What color are the calls going to be? Is the navigation bar going to be the default color or something custom? What about the buttons? What about the sounds that are made when the user touches something? The designer takes the user interface and creates all the files needed in either Adobe Photoshop or Illustrator to make the application look the way it is supposed to. This is no easy task, as every element must come together in harmony and evoke some sort of feeling in the user. For some of the best application design inspiration, I recommend subscribing via RSS to the dribbble iPhone category. Dribbble has some of the worlds best designers and I am always blown away by the quality of these application designs.
As an example, let us take the “Deliveries” application by JuneCloud. This application was created to make it really easy to track your packages.
What makes this application really shine is not just what it does (it tracks your packages and organizes them really well), but how it looks and feels. Take a look at the application icon.
The icon actually looks like a package with a tracking number, telling us what the application does without even reading the title. There is shipment tape on the icon, like any shipment would have on it, and a shipping label with a barcode on it. It is also raised, like a box would be, which makes us think it is a real box, right there on your home screen.
The first screen of the application shows you all of your shipments, and the cells are colored based on the carrier (brown for UPS, purple for Fedex, etc). The days left until the shipment arrives is a huge number that is really hard to miss, and the tableView makes it easy to see the relevant information quickly. These visual ques let the user know exactly what they are looking at without having to search for information. The text on the cell is a lighter shade of the cell color, and the cell design makes us believe the cells are actually popped out of the screen and coming towards us. The background of the tableView is a dark tealish color, which matches perfectly with the color of your packages. The application feels like a real package tracking app.
On the individual package screen, the navigation bars and the tableView background all change color depending on which package you are tracking (brown for UPS, purple for Fedex, etc).
The Packages application is very well designed, and the thing to note here is that the design completes the application. It would have been possible to ship the application with the default iPhone colors, and it would have behaved the same way, but the design makes the application feel right, and actually work better. It looks like what is it supposed to look like, and gives off visual ques to the user using the right colors, and gradients to let the user easily discern what they are looking at and find what they need quickly.
Keep in mind, ideally, there would be 3 different people working on an application, each speciailized in one area, but more often than not, the different people working on an application share responsibilities. In the application I am creating for the Bayyinah Institute, I am all 3, the UI designer, the designer, and the iOS developer. I think it helps to know a little bit about each discipline so you can be a well rounded individual who can help out when others need help, but definitely have a specialty that you work every day to master.
Finally, it is the iOS developers job to take the user interface and the design and make the application actually work. This is where the UIViews and the UITableViews, NSArrays, etc get written and the application is given life. I have heard arguments that the designer’s job is more important than the developer’s because a developer can’t make a ship-able application that any user will actually want to use, but the opposite is also true. The first iPhone was born only when these 2 disciples, design and computer science programming, came together harmonionsly. Everything not only looked amazing, but functioned flawlessly and intuitively. These 2 disciplines could not be further apart, I mean, one is entirely artsy and all about feeling, aesthetics, and beauty, and the other is all about science, methodology, and rigidity. (There is definitely an art to programming, but a different kind of art…) It is only when all 3 of these, the UI designer, the designer, and the iOS developer come together and respect each other’s disciplines that an amazing application gets shipped.
[HOW TO] Get iTunes Podcast RSS Feed
In an app I am creating, I would like to show a list of the available podcasts in an UITableView by parsing the RSS feed. The problem is thet you can’t get the RSS link for the podcast from iTunes.
If you need the RSS link for any podcast, you can get it here:
[HOW TO] Open other Apps from your App
I am working on an application that should open up the Facebook app when a cell I created is touched. The following link shows you how to do this with not only Facebook, but Youtube, iTunes, Mail, Sms, Maps, and much more.
<How to open other applications from your application>
Specifically for Facebook:
NSURL *url = [NSURL URLWithString:@"fb://<insert function here>"]; [[UIApplication sharedApplication] openURL:url];
You can use these options:
- fb://profile – Open Facebook app to the user’s profile
- fb://friends – Open Facebook app to the friends list
- fb://notifications – Open Facebook app to the notifications list (NOTE: there appears to be a bug with this URL. The Notifications page opens. However, it’s not possible to navigate to anywhere else in the Facebook app)
- fb://feed – Open Facebook app to the News Feed
- fb://events – Open Facebook app to the Events page
- fb://requests – Open Facebook app to the Requests list
- fb://notes- Open Facebook app to the Notes page
- fb://albums – – Open Facebook app to Photo Albums list
[Big Idea] Introduction to Core Data Classes
One of the most important thing an iOS developer needs to do is be able to manage data, from it’s creation to it’s death. Without being able to move data around, add new data, and delete it, you really take your apps to the next level.
The Apple SDK gives you many ways to manage your data, the most popular of which are NSUserDefaults (which is really a toy when it comes to data management), Archiving/UnArchiving , using an SQLite database, and Core Data. Core Data actually uses an SQLite database engine to store your objects and control them. There are benefits and drawbacks to using each method, and while Core Data might seem like an untamed beast to the beginner, it is really the best way to go if you are going to be saving 500+ instances of objects in your application. Core Data essentially lets you use a SQLite database without knowing any SQLite database commands. It lets you talk to the database in Objective C, and simplifies many other things for you. Creating the objects is extremely simple, and can be done through the graphical Cora Data model screen.
In this article, I will explain the main Core Data classes and how they interact with each other. There will be some code that might scare you a little, and that is ok, we will be discussing the concept behind it so you can understand what is going on first. There will be a detailed tutorial coming soon.
When you create a new application and check the “Use Core Data” box, XCode will create many files for you, including a model file, which has the codec “.xcdatamodel.” This file is where you create your “model”, or table in a regional database. In a regional database table, each table will represent a type. For example, you can have a table of people, a table of credit card purchases, a table of real estate listings, etc. Each table will have a number of columns to hold information about that thing. A table that represents people might have a column for the person’s firstName, a column for his lastName, one for his socialSecurityNumber, height, age, etc. Each row in the table represents a single person. (From left to right, a person with firstName “Bob”, and lastName “Smith” has a socialSecurityNumber of “xxx-xx-xxxx”, etc). This translates very well into Objective C, each row is an instance of an object (in this case, an instance of a Person class), and each column is an instance variable (the height column is the height property on the Person class, the age is the age property on the Person Class, etc). Thus, it is Core Data’s job to move data to and from these 2 organizations.
In Core Data, a regional database table is called an Entity. (The Person class above is the Entity). Each instance variable (property of Person) is an attribute. A Core Data model file is the description of every entity and their attributes in your application. It also deals with how to link entities to others (for example, a Leader entity can have many follower entities under him), and has different kinds of relationships you can give eitities to each other, but that is beyond the scope of this article.
Let us talk about some classes that you will interact with when dealing with Core Data:
NSManagedObject
Once you specify your model file and create all your entities and attributes, while selecting the entity files, press command + N to create a new file, go under “Core Data” in the left pane, and select NSManagedObject Class. When you do this, XCode will create for you a .h and a .m file for each of the entities you selected. If you take a look at their superclass, it will be NSManagedObject. When an object is fetched with Core Data, it’s class is by default, NSManagedObject. NSManagedObject works like a dictionary in that it holds arbitrary key-value pair for every property in the entity.
When an NSManagedObject is created from one of your entities, the accessors and getters will be created for you, using the @dynamic property. Recall that when you define a class, it’s properties will look like:
@property (nonatomic, retain) Person *aPerson;
you then go into the implantation file and @ synthesize the property to be able to set it.
Core data creates the files with @dynamic properties, so you don’t have to do any synthesizing or declaring them. You can set and get them automatically. (Core Data uses a dictionary like ability to SetValue: For Key).
NSManagedObjectModel
This is the model file in which you created your entities and attributes.
NSPersistentStoreCoordinator
You will never interact with this directly, but it is the gatekeeper between you and the database. It used the model file in the form of an instance of NSManagedObjectModel and opens a SQLite database at a particular filename.
NSManagedObjectContext
This is the class you will interact with to do all of your fetching/saving. The NSManagedObjectContext is called on when some change needs to happen to your database (add a file, remove a file, etc).
When you create a Core Data app, in the AppDelegate header file you will see 3 readonly properties with these files. The AppDelegate needs to create an NSManagedObjectContext that you will use to interact with the database, but it will need to create 2 other objects in order to do that.
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectcContext;
If you look in the AppDelegate implementation file, you will see that there are explicit getters for these properties created.
Initialization of Core Data starts with loading the data model into the NSManagedObjectModel object. The second step of the initialization sequence is to create and bind the persistent store through NSPersistentStoreCoordinator. Finally, create an NSManagedObjectContext that your code interacts with in order to store and retrieve data.
The first thing that XCode creates for you is the model, which is derived from your .xcdatamodel file.
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil)
{
return __managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@”Sumaya” withExtension:@”momd”];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
The -(NSManagedObjectModel *) in the method name means we are returned an NSManagedObjectModel when the method is called.
The next thing that is created is the NSPersistentStoreCoordinator, which binds the store to the database. The code below say that is the persistentStoreCoordinator is not equal to nil (if it exists), then return it. If not, then create it (addPersistentStoreWithType:NSSQLiteStoreType)
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn’t already exist, it is created and the application’s store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@”Sumaya.sqlite”];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
{
NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);
}
return __persistentStoreCoordinator;
}
The last step is the create the NSManagedObjectContext, through which you talk to the database and have it do cool stuff. In the code below, we say, if the managedObjectContext is not equal to nil (meaning, it exists…) then return it. If not, then allocate and initialize it (__managedObjectContext = [[NSManagedObjectContext alloc] init];) and set it’s NSPersistentStoreCoordinator, so it knows which database to speak to. ([__managedObjectContext setPersistentStoreCoordinator:coordinator];)
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil)
{
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
__managedObjectContext = [[NSManagedObjectContext alloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
Part II and a detailed tutorial of creating an app with CoreData is coming soon.
Resources:
Apple’s own iOS Core Data Programming Guide is an excellent resource, but I find that Apple’s documentation a little too advanced for the beginner.
[Big Idea] Introduction to Model-View-Controller System for iOS Applications
If one wants to master iOS development, one must master three subjects, in this order:
1) Objective C. Objective C is the language that you speak with to the compiler to tell it to do what you want. Like any language, this takes time to learn and can only be perfected with time. There are many nuances and differences between Objective C and other computer programming languages. The good thing is that there are a ton of books on Objective C that one can use to get started, the best one being “Objective C Programming, the Big Nerd Guide.” The official Apple documentation also has a good introduction to Objective C, although it is a little too complex for beginners.
2) Master the big ideas. There are several concepts in iOS programming that are essential to writing any kind of application. These include delegation, memory management, how to use view controllers, model-view-controller theory, etc. These take a few weeks to really sink in, but mastering them is crucial.
3) The Frameworks. The iOS SDK is essentially a number of different frameworks, each specializing in a certain task. For example, the MapKit framework is in charge of displaying a map, and in it you will find methods that will help you add annotations to a map, display parts of the map, zoom in on a map, change the type of map, etc. Each framework deserves its own class, and defines its own methods. The good news is that you won’t need to learn all of them. Some apps won’t have to deal with maps, others will. It is important to know a little about all the frameworks, or at least how to use them, and specialize in one.
I started reading the Big Nerd Ranch Introduction to iOS programming, which is very easy to understand and easy to implement. I highly recommend this book for anyone who wants to begin learning how to develop iOS applications.
This article will explain the model-view-controller theory.
iOS applications are developed in pieces, and the three main kinds of pieces you will need to know about are models, views, and controllers. Together, these pieces work together to make an app work. The goal with this type of design is to maintain a distinction between the three functional aspects of an app that display information to the user and allow the user to interact with the app.
1) Model- The data and data management of the application. This is the heart of any application, the logic that the app uses to interact with data.
Model objects are usually subclasses of NSObject, and should be reusable. Suppose you finished writing an app for iOS but want to port it to the Mac. If you followed the MVC practice closely, you can literally paste all your model files into the Mac app and start from there. This is where real computer programming is done, the model files. Getting and retrieving data when you need it is actually the hardest part, but once you master it, you have complete control.
Here is an example of us creating a model file and saving it. We create a newTeam in a view controller, give it some attributes, and save it by invoking the “saveTeam” method in the model, which we will implement somewhere else in our code.
Team *new Team = [Team alloc] init];
newTeam.firstName = @”RedSuns”;
newTeam.uniformColor=@”Red”;
[Model saveTeam];
2) View- What the user actually sees on screen and is able to interact with. Views are all descendants of UIView, and they are what the user actually sees on the screen, everything from images to scrollViews, tables, labels, etc.
3) Controller- The mediation between the model and the view.
Let us consider an example: An app that displays the names of employees working at a certain company.
- A UILabel that shows the actual name of the employee is just a view. It displays a number of pixels in a certain order to form letters on the screen, and that is all it knows how to do. It does not know WHAT to draw, just HOW to draw it. The actual name of the employee is located somewhere else. The view should reflect the name, but never store the name.
- The employee names are stored in the model. This could be an NSArray or an NSDictionary with the names of employees in it, in a separate class. The model handles and stores all the data of an application.
- Telling the employee name when to change is the job of the view controller. Let us assume that the user touches a different employee name in our app, and now a new employee must be fetched from the model and displayed on the screen. This is the job of the view controller- to control the actual data from the model and how/when it gets displayed in the view. If the user goes from one screen to the next, which view should now be displayed on screen? The view controller pushed views onto the screen and pops view off the screen depending on what you put in your code. It mediates between the view and the model.
This example shows the power of the MVC model. By separating the data management away from the actual view and having their interaction being controlled by a view controller, you can essentially make huge changes in your app by only changing one of these and not having to touch the others. Want to display the text in a different font? Change the UILabel’s font property in the view controller. Want to change what data gets transferred into the view? (Which employees get shown on screen?) Change the model. This also makes for an apps reusability. We can take the view that we created and put it into a completely different app, and it will work with whatever model it is now connected to. The very names of the Cocoa classes reveal the MVC philosophy. A UIView is a view, a UITableViewController is a Table view controller. By keeping the MVC architecture in mind as you develop your app, you will make it very easy to know where each piece of code should go.
Sometimes, you will be tempted to combine these three different objects into each other. Resist! Creating an app that you are proud of means doing it right, even if it might add a few steps in the middle. The MVC structure is there to help you organize your code and make it easy to find and edit it later. A golden rule in iOS programming is that you only include what a class needs in it’s files, and nothing else.



























