Using NSNotificationCenter to Facilitate Event Handling From Inside a UITableView

Leave a comment

Something that really impressed me as I started learning iOS development and Objective-C is how easy it is to communicate between classes. One great way to do this is by using NSNotificationCenter. I use NSNotificationCenter a lot, and one place it’s been especially useful is event handling for buttons inside the cells of a UITableView. This post will first discuss using NSNotificationCenter as a way to implement event handling inside a table and has code examples in the bottom half of the article. It’s simple to implement as there’s just three pieces of code one needs to use to get a notification working.

In one of the projects I work on, we have a multi section table where each section represents a subset of all possible options. Each section has a header (which is an instance of a custom UITableViewCell, HeaderCell) with buttons on it for the user to tap to perform many functions such as selecting items included in that section, renaming and deleting the section, etc. The first thought  a new iOS developer may have is that all the event handling for the buttons being pressed should be in the HeaderCell class. That turns out to be tricky, because the HeaderCell is not providing its own data, nor can it directly trigger a refresh of the contents of the table. There is a UITableView data provider, which is the ViewController which is responsible for the view containing the UITableView. It would be possible to build public facing variables or functions to the ViewController to allow the HeaderCell to handle its events directly by modifying the data structures inside the ViewController, but this gets messy and isn’t ideal. It’s much better to have the ViewController manage all of the table data exclusively.

Instead, the thing to do is post a notification to NSNotificationCenter when one of the buttons in the HeaderCell is pressed. The ViewController then receives this notification, along with the object that sent it, allowing it to handle updating any data and UI being affected by the event, all  while maintaining complete control over its data.

Here’s an image of the top of one section of the UITableView. The HeaderCell is the area with a green background. To handle the buttons being pressed inside the HeaderCell, we use NSNotificationCenter.

 

To implement the HeaderCell’s role in the event handling, it simply needs to post a notification when a button was pressed. This is done with the function below contained inside the HeaderCell class. Remember to link the button with this function in Interface Builder.

-(IBAction) gearPressed:(id)sender{

    NSLog(@”Gear Pressed”);

    [[NSNotificationCenter defaultCenter] 

        postNotificationName:@”GearButtonPressedNotification” 

        object:self];

}

The ViewController requires two pieces of code to complete its role in this event handling. First it needs to be “listening” for the notification, aka being an observer of the notification. This is done before any notifications have been posted, so I always put the following inside the viewDidLoad function:

   [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(gearButtonPressed:)
                                                name:@”GearButtonPressedNotification”
                                              object:nil];

Notice two things about this:
1) The “name” provided matches exactly the string used by the HeaderCell for postNotificationName. If these two are not the same, the message will not be received.

2) the “selector” indicates what function will be called when the notification is received.

Which brings us to the last section of implementing event handling via NSNotificationCenter, doing the actual updates to our data! The following function is contained in the ViewController class as well. This is where I finally update the affected data and UI.

- (void) gearButtonPressed:(NSNotification *)note {
   NSLog(@”received gearpressed event”);

   NSIndexPath *selectedPath =

        [dataTableView indexPathForCell:(HeaderCell*)(note.object)];

    NSLog(@”%d”,selectedPath.section);

   …
}

In the gearButtonPressed function, the first thing to do is figure out which section sent the notification, because it indicates what data needs to change or where a UI element needs to be drawn. The details of what my program does when this event is detected isn’t relevant to this tutorial, but it is important to see how easy it is to determine which element of the table sent the notification.

Hopefully this post gave you insight into one of the great features of Objective-C and iOS development, simple message passing between classes. If you follow the structure laid out in this article, you’ll be able to maintain good MVC practices and keep the scope of data access to the controller class.

Weekly Roundup – May 25

Leave a comment

Facebook has its eyes set on the mobile horizon

It is a well known fact that the Facebook app / mobile experience is lacking.

This image sums up the majority of my experience with Facebook’s mobile app. I know I’m not the only one. Facebook has been rumored to be working on their own smartphone and even if this is not true I think they should be.

Imagine if the Facebook Mobile experience could be as seamless as the desktop experience. That is why it is a big deal when rumors of an Opera acquisition start going around. While Opera isn’t the most popular browser it does boast an extremely impressive mobile market with over 168 million (mobile) users in March alone.

Whether or not this deal will transpire is beside the point that Facebook needs to improve their mobile experience. It doesn’t do much good to wait ~20 seconds for a news feed that I want to check for ~10 seconds while on the go.

The full story is available here

Facebook officially declined to comment.

 

 

 

Siri-ous problems

IBM bans Siri from Employee phones

It was released this week that all the data you have ever spoke to Siri, incidentally, has been recorded by Apple.

Full Story

Siri changes answer to the “Best Phone Ever” question

Apple may have noticed, from all their data tracking, that the question “What is the best smartphone?” was being asked by many users. Prior to this week Siri did as it should, answered honestly from a search of customer feedback.

While I personally wouldn’t agree that the Nokia – Lumia 900 is “The Best Smartphone” at least it provided an honest answer. This is what you will see now if you ask Siri what the “Best Smartphone” is.

This answers seems a bit more subjective…

Siri was also updated to include a sarcastic response “You’re kidding, right?”

Gamerchanger of the Week

The Moai, Easter Island giant head statues, have … wait for it… buried bodies!!

Pictures of an Excavation

 

Weekly Roundup – May 18

Leave a comment

To Learn to Code, or Not to Learn to Code.

One of the top stories of the week was the reaction to the new ‘Learning to Code’ fad.

Websites like CodeAcademy began offering services, (ie. CodeYear) for users who want to get their feet wet in the coding world. A popular article surfaced this week begging people ‘Please Don’t Learn to Code‘. While the article makes a good point, learn to code only if you have a reason to, the title created more than a few ripples in the interwebs.

The most popular rebuttal to this article is Sacha Greif’s ‘Please Learn to Code’.

“Learning to code” doesn’t always mean becoming the next Linus Torvalds, just like “learning to cook” doesn’t mean opening a 3-stars restaurant.

It simply means having a basic grasp of how computers work instead of blindly following whatever a talking paperclip tells you.”

Justin, from the creator of, JustinTV, wrote a great insight into why coding can help even when you’re not a programmer and in the end A couple hours of effort saved him four days of repetitive work.

“Alright guys I think we’re good”

 

Focusing on Integration, not Innovation.

A slightly morbid story about  How Yahoo! killed Flickr

Although Flickr grew tremendously with the huge influx of Yahoo users, the existing community of highly influential early adopters was infuriated. It was an inelegant transition, and seemed to ignore what the community wanted (namely, a way to log in without having to sign up for a Yahoo account). This was the opposite of what people had come to expect from Flickr. It was anti-social.

The site that once had the best social tools, the most vibrant userbase, and toppest-notch storage is rapidly passing into the irrelevance of abandonment. Its once bustling community now feels like an exurban neighborhood rocked by a housing crisis. Yards gone to seed. Rusting bikes in the front yard. Tattered flags. At address, after address, after address, no one is home.

The CEO of Yahoo! , Scott Thompson, was seen removing Flickr from his resume, adding  that he ‘Had the initial idea for Instagram’.

The future of Physics Classes?

MIT released a Video this week of a magnetic field that is interactive.

What is the practicality of this you ask? Good question I say. Yet for some reason, Real Life Angry Birds: Space comes to mind.

Weekly Roundup:

Wil Wheaton posts about the absurdity of banning Torrenting in general

Iceland uses Facebook to re-write its constitution

The idea of  creating a gitHub account to include amendments is being thrown around.

How to Load your Scripts asynchronously 

816-Bit computers 

Office Update

Leave a comment

It’s been a busy few months at Hardin DD! We’ve welcomed five new developers to our team, and have also hired Dennis Axelrod as our director of sales and marketing. In addition, we’ve made a concerted effort to focus on decorating and branding our offices, and we are working on a complete redesign of our website. Below are some of the pictures of our more interesting office artifacts, including our very own Death Star:

Google ‘Plays’ With Fire

1 Comment

Google playfully decided to change the name of their Professional and well respected ‘Android Market’ to encompass additional devices, ie. GoogleTV. Despite the obvious complaints about the decision of the new name ‘Google Play’, Google really could not have made the conversion worse if they tried. Granted when you opened the ‘Market’ there was an obvious pop-up that told users the store was being ‘upgraded’ to ‘Google Play Store’ which they had to agree to before entering the store. This takes into account that users read pop-ups before hitting accept. Where Google really went wrong was by not replacing the ‘Market’ Icon with the ‘Play Store’ Icon. It was just gone. This sparked a whole plethora of confusion with users outraged, spouting things like a virus deleting their market to, my personal favorite, blaming their child for deleting it.

Angry Users

It’s well known that people largely don’t read click-through text. It’s simply a usability issue. It’s something that pops up and blocks the user from what they want to see or accomplish. The (average) user instantly does the logical thing and dismisses it (agrees to it) ASAP so they can get on with their task. You can’t even blame the user for this response, Google needs to take this opportunity to learn from this experience. From now on when they are going to make sweeping changes that require a user to click ‘I accept’ they should also blast an audio file “THE ANDROID MARKET IS NOW  GOOGLE PLAY. THANK YOU FOR NOT FREAKING OUT AND CALLING TECH SUPPORT”

Also, I was quite excited to rent movies directly on my phone for $0.99. It is cheaper and much more convenient than redbox. Then there was this:

While the decision to offer rentals to rooted users isn’t even within Google’s control, it’s a backward model of control. It is denying users that WANT to pay for a rental. If a user is going to torrent, a user is going to torrent. By blocking rooted users over the fear of them copying the file to their phone they are really just turning down paying customers.

Don’t piss off your market app or it will be deleted off your phone by itself.

Finally Decorated My Office!

Leave a comment

At Hardin DD we’ve been rapidly growing over the past year, and we moved into our new, bigger offices in June. However, between working to grow the company, programming around the clock, and getting married in July, I have neglected my personal office. Until now… I just wanted to post some pictures to give our readers a sense of what our offices are like. Hopefully Scott Resnick will follow my lead as well and decorate his office at some point. You should visit us sometime!

 

3D Printing and Pirate Bay: Star Trek’s Replicators?

1 Comment

If you’ve ever watched any of the Star Trek variants other than the original series, you’re familiar with the replicator: a device that can replicate pretty much any physical object, for free, using base materials like proteins, carbohydrates, plastics, metals, et al. The replicators make food, drinks, and a whole host of devices and inanimate objects. The only thing they are unable to do is produce living things. This may seem like a far fetched invention, in the same category as time travel, transporters, and warp drive, but advances are being made in technology that seems to be headed in that direction. Slashdot, along with ZDNet, is reporting that Pirate Bay is now creating an archive of torrents called physibles, which are downloadable files that can be fed into a 3D printer (such as the RepRap) to produce a physical object:

We’re always trying to foresee the future a bit here at TPB. One of the things that we really know is that we as a society will always share. Digital communication has made that a lot easier and will continue to do so. And after the internets evolutionized data to go from analog to digital, it’s time for the next step. Today most data is born digitally. It’s not about the transition from analog to digital anymore. We don’t talk about how to rip anything without losing quality since we make perfect 1 to 1 digital copies of things. Music, movies, books, all come from the digital sphere. But we’re physical people and we need objects to touch sometimes as well! We believe that the next step in copying will be made from digital form into physical form. It will be physical objects. Or as we decided to call them: Physibles. Data objects that are able (and feasible) to become physical. We believe that things like three dimensional printersscanners and such are just the first step. We believe that in the nearby future you will print your spare sparts for your vehicles. You will download your sneakers within 20 years.

The blog writer from the Pirate Bay clearly grasps the potential significance this for society, specifically along the lines of how replicators are used in Star Trek:

The benefit to society is huge. No more shipping huge amount of products around the world. No more shipping the broken products back. No more child labour. We’ll be able to print food for hungry people. We’ll be able to share not only a recipe, but the full meal. We’ll be able to actually copy that floppy, if we needed one. We believe that the future of sharing is about physible data. We’re thinking of temporarily renaming ourselves to The Product Bay – but we had no graphical artist around to make a logo. In the future, we’ll download one.

Obviously 3D printing technology is very far from being able to replicate food, or anything biological, but it is already used regularly for prototyping mechanical devices, and is rapidly advancing. As an example, the above image is a fully functional flute that was created by a 3D printer. It will be fascinating to see it evolve over the next 20-30 years.

Evolution of Video/Pictures

6 Comments

With a quick glance around the web (or if you follow technology to any extent), it’s quite apparent that the ability to capture visuals continues to become more incredible; whether it’s 3D, HD, gigapixel stills, or panoramic video.

My first thought on this note is the View-Master (from the 60s!).  This allowed you to view single images through a private viewing device, which has grown to now allowing private video viewing through transparent glasses (article and video)!  On that note, similar glasses are able to record 720p video (article and video) while remaining incredibly discreet.  Now that mobile devices can support 720p or 3D video recording, where else to go besides the full 1080p?  Well, 360 degrees.  On display at CES, there is an adapter for the iPhone for $80 that allows you to view and record video 360 degrees around (which puts to shame this lousy awesome,  panoramic ball camera).  Another amazing improvement, which has actually been around for a year or so now, is a light field camera that captures a photograph that can be focused later (there’s a fun example to play with at that link).

I hope that the interesting uses of these have yet to be discovered, and are not actually the technology itself, but instead come via the popularity of the devices and creativity of their users.  Just imagine (not sure if it will ever actually be possible) what you could do with a light field of HD, 360-degree, 3D video.  Mind. Blown.

 

iWebcomix Update

8 Comments

The first week after iWebcomix launched has been a lot of fun. We have many users in 26 different countries now, and have served over 15,000 comics to our users. We’ve gotten some very good and helpful reviews on the app store, and are excited to see our user base continuing to grow at an increasing rate. We’re getting ready to roll out our first update, which will feature the ability to share comics on Facebook, the ability to mark all issues as read for a given comic, and include the following new comics:

  • A Series of Cats
  • Dorkly
  • Empire of Apathy
  • Endless Origami
  • Folly and Innovation
  • Guinea Something Good
  • Happle Tea
  • Mark Doesn’t Understand Animals
  • Married To The Sea
  • Mr. Lovenstein
  • Nothing Nice To Say
  • Peanizles
  • Professor Hobo
  • SBBoard
  • The Magnificent Whatever
  • The Optimist
  • Toothpaste For Dinner
  • Whomp

We’ll continue adding more comics after that. If you haven’t downloaded the app already, you can get it at here!

 

More

Designing and Developing Applications in an Ever-Changing Mobile Space

3 Comments

I recently gave a talk to the Middleton Chamber of Commerce about mobile application development, especially related to fragmentation of devices and operating systems. I thought it would be worth posting here, so here it is:

Older Entries Newer Entries