Archive

Posts Tagged ‘iPhone’

Threads and Waiting

August 24th, 2009

Proper use of threads will do wonders for your program’s responsiveness. It will also do wonders in making your code harder to follow. What if you have a thread churning along in the background and you’d like to know when that thread has produced a value before continuing on with your work? Maybe you have a thread called ComputeWinningStockThread that takes all the data from the stock market, applies some magic formula and spits out stocks that are going to make you millions in random time intervals.

1. Start ComputeWinningStockThread in background.
2. Until ComputeWinningStockThread has picked a stock, continue checking to see if it has.

This is the poor man’s version. It is also called the busy loop or polling. And it uses up valuable resources that your iPhone could be using for other things.

The proper way to handle this is with the NSConditionLock. You can use NSConditionLock to have one thread wait for notification from another thread before continuing. Or, in other words, it blocks until a condition is met (hence, the name conditional lock).

In Objective-C, this is the gist of what you would have to do.

1
2
3
4
5
6
7
- (void) ComputeWinningStockThread {
    while (YES) {
        [myLock lock];
        winningStock = [self someSecretAlgorithm];        
        [myLock unlockWithCondition:0];
    }
}

Then maybe in another message, you are calling this thread to earn your millions.

1
2
3
4
5
6
NSConditionLock *myLock = [[NSConditionLock alloc] initWithCondition:0];
[NSThread detachNewThreadSelector:@selector(ComputeWinningStockThread) toTarget:self withObject:nil];
 
// This will block until it is unlocked in the thread
[myLock lockWhenCondition:1];
NSLog(@"I have a winning stock! %@", winningStock);

If you enjoyed this post, make sure you subscribe to my RSS feed!

Development, Objective-C, iPhone Development , , , , , , ,

Memory Management Pitfalls

May 21st, 2009

I thought that, for the most part, I was done with memory management after moving on from C/C++ to Java. But we all know that was not to be, so I’ve created this quick reference sheet for my own reference that some of you may find useful.

Pitfall 1: The order matters
Assume we have a setter method in some class.

1
2
3
4
5
6
7
8
9
-(void) setText:(NSString *)newValue
{
   if (newValue != text)
   {
      [newValue retain];
      [text release];
      text = newValue;
   }
}

The NSString that is passed into setText may be another NSString. So the value that is passed in must be retained, because we can’t have the memory freed until we are done with the class. We release text because it is being repaced with newValue.

Note that it is wrong the write the code above as

1
2
3
4
5
6
-(void) setText:(NSString *)newValue
{
      [text release];
      [newValue retain];
      text = newValue;
}

This is a due to a somewhat subtle case when text and newValue points to the same instance of NSString. By releasing text, newValue will also be released.

Pitfall 2: Using the dot (’.') notation incorrectly

self.text = newText

is actually a shorthand form of

[self setText: newText]

Thus, it will retain newText, increasing the reference count. Do not confuse it with how it works in a language like Java.

this.text = newText

is different from

self.text = newText

Because the first is a direct assignment and the second is actually a message call.

Pitfall 3: Not following the fundamental rules of reference counting
The fundamental rules are:
1. If you allocate, create or copy it, you need to release it.
2. If you retain it, you need to release it.

Consider the following snippet of code

SomeObject *newObject = [[SomeObject alloc] init];
self.object = newObject;
[newObject release];

newObject needs to be released to balance the retains. The first retain is in the alloc call, and the second retain is in the setObject (aka self.object = newObject) message.

Also, if you write something like this

self.object = [[SomeObject alloc] init];

the retain count will be at 2 because it is retained once for the alloc and one more time for the setObject message.

If you’d like to read more about memory management, here is another post that I wrote about the topic (I also talk about NSAutoReleasePool a bit here).

This wasn’t a comprehensive overview of memory management, but I hope it was somewhat helpful.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Development, Objective-C, iPhone Development , , , , ,

Tale of Search Woes

May 7th, 2009

I don’t know what has been going on (actually, I do), but we have been seeing a statistically significant increase in the sales of iHappyBirthday. It wasn’t too long ago that we noticed that our application would not appear in the search results if the search terms were “happy birthday”, though it was still search-able with the term “birthday”. It was odd because it has always been search-able by “happy birthday.”

We emailed Apple about it, and the response we got back was pure hilarity.

Search results are working as expected at this time. App Store search results are based on several factors determined by Apple-confidential algorithms.

I’m not sure what this super secret “Apple-confidential algorithms” were that made it unsearchable by “happy birthday”, but it at least it did make us laugh. It was most likely a canned response because search was actually broken.

Anyways, we didn’t realize how important it was for our application to be search-able by “happy birthday”, because as soon as search was fixed, our sales have doubled (albeit from a small number, but welcome none the less!).

If you enjoyed this post, make sure you subscribe to my RSS feed!

News and Updates, Opinion ,

Back from the Dead

April 24th, 2009

It’s been very quiet here. Life has once again conspired to get in the way of our goals and dreams. My full time job has been keeping me busy at 70 hours a week. As much as I wanted to work on my iPhone project, I do enjoy what I do for a living, and one of my long term goals in life is to foster my career. Actually, allow me to impart some wisdom in light of the current economic crisis. I actually believe that investing in your career and education is the best investment that you can make (and not in retirement accounts, though it’s a good idea). I recently had my midterm as well, so that also kept me away from working on our second application.

The schedule is starting to regain some semblance of sanity, so I will be able to devote more time to the iPhone project once again. The lack of time is only part of the reason for the delay, however. We decided to totally abandon the current design and go for something more innovative and creative. I’m not actually sure how well it will be received, but we noticed that there are too many of the same old and tired interface designs on thousands of applications. Though our application might be interesting, we felt that the interface design may hold us back. So a paradigm shift in our thinking and a total overhaul of the interface was required in order to stand out from the crowd.

Wish us luck!

If you enjoyed this post, make sure you subscribe to my RSS feed!

News and Updates ,

iHappyBirthday 1.1, what next? SaS.

February 6th, 2009

We just go approved for the iHappyBirthday update.  A small drama right before the release, but nothing we couldn’t laugh off.

I just want to let people know that the 24:2 blog post ratio that Min has over me is due to the fact that we’re hard at work with our next upcoming App: codename SaS.  Stay tuned.

If you enjoyed this post, make sure you subscribe to my RSS feed!

News and Updates , , , ,

Rejection Hurts

February 5th, 2009

The update to version 1.1 of iHappyBirthday was rejected by Apple because the application did not meet the iPhone Human Interface Guidelines. The detailed reason for the rejection is because we do not display a checkmark next to a selection in our choose cake screen. Apple says that you must provide feedback to the user so that the user knows something is selected.

It’s kind of funny, because it’s obvious what the user has selected because the item that the user has selected is highlighted. It’s also funny because our version 1.0 behaves exactly the same way and it was approved. This just seems to be a case of having gotten a reviewer who is a bit more thorough (or anal — take your pick). In any case, we resubmitted the application immediately after fixing the issue. But that does delay the release by another week or so because now it’s pushed to the back of the review queue. Boo.

And a final word of warning to anyone releasing an update. Do not set the release date to a date in the future, because that will also affect the release date of your original version. We set the release date of our update to a future date, and that also affected the release date of version 1.0. The net effect being that version 1.0 was taken off of the App store because the availability date was set to future date! We were really perplexed by this one. We thought Apple retroactively took applications off of the App store if the update to the original application is rejected. Who would have figured that the release date of the update was tied to the original version. Apple should really make this clear.

On a more personal note, I am strangely enjoying school. Is it because I’m getting older? My brain still seems to be fairly functional because I am able to soak up new information. Let’s hope this continues.

If you enjoyed this post, make sure you subscribe to my RSS feed!

News and Updates , , , ,

A Few Tidbits

December 29th, 2008

Being that the iPhone is a multimedia device with multiple input sources that actually works well as a multimedia device with multiple input sources, I ran into quite a challenge when I tried to implement a few features that took advantage of this fact. The biggest challenge of them all was the implementation of the Fast Fourier Transform (FFT) algorithm for a discrete signal from the built in microphone.

I dozed off during the lecture when the professor was talking about the Fourier analysis and FFT.  The algorithm itself wasn’t too hard to implement because there is an abundance of information on the internet.  But what did prove to be a barrier was the technical details (and also limitations) of the iPhone.  For example, I had to somehow intercept the audio packets from the microphone and send the data off to my FFT function for analysis.

The program ran fine on the iPhone simulator, but I ran into performance problems on the device itself.  Another problem I ran into was figuring out what to send to my FFT function.  I got the best results by converting the bytes passed into the AudioQueue’s callback function into a 16 bit, big-endian, signed short integers.  By best results, I mean that the program can distinguish between different frequencies reasonably well.  I’m not sure whether the frequencies are correct, but I achieved what I was aiming to achieve, so I’m happy with the results.

I’m still trying to figure out the best way to recognize different sounds.  But this is a big and complex field of study that I don’t expect to solve in just a few nights of study, so I will have to come up with a reasonable heuristics to achieve my goal.  I’m at a point where things are working adequately, but I’d still like to see if I an improve it a little more.

Finally, this little piece of fact drove me nuts.  I was trying to detect a touch on an UIImageView.  It turns out that in order for it to receive events, you have to explicitly turn on “User Interaction Enabled” and then subclass UIImageView and override the callback function.  Had I read the documentation a bit more instead of jumping into it…  Oh well.

The application is still on schedule for the end of January release date.

Hope everyone had a great Christmas!

If you enjoyed this post, make sure you subscribe to my RSS feed!

Development, iPhone Development , , , ,

Almost There…

December 23rd, 2008

The iPhone application that I am working on is almost ready for prime time. I expect it to be in the Apple App Store late January or early February.  It’s already been almost three weeks since I started this journey.  I expected it to be a smoother ride, but I was seriously sidetracked.  Or rather, I sidetracked myself. 

While working on the project, I got interested in 3D modeling and animation.  This new found interest really derailed me from the goal at hand.  I also picked up OpenGL again after ignoring it since I took a class in computer graphics back in college.  I even played around a bit with a game engine and was literally blown away by what it can do.  You can literally write a commercial grade game in less than a week without having a deep knowledge of 3D programming.  I thought about going this route, but at the moment, I don’t have any plans to release 3D iPhone applications.  And also because the license to purchase the game engine is fairly expensive.  But when I do come up with an idea for an application that requires 3D, then I know where to look.

We have another project in the pipeline that I am immensely excited about.  So please stay tuned for more announcements in the future.

And a Merry Christmas and a Happy New Year to everyone!  I hope this year brings you bountiful fortune, joy and happiness!

If you enjoyed this post, make sure you subscribe to my RSS feed!

News and Updates , , , , ,

Xcode Interface Builder

December 12th, 2008

My learning style is such that when I learn something new, I jump into the fire and deal with the repercussion as they come.  This approach has gotten me into a bit of trouble in the past, but for the most part, it has served me well.  I tried a similar approach a few days ago attempting to write my first iPhone Cocoa Touch application.

The stumbling block was the NIB vs. the XIB interface files.  I have had experiences with Visual Studio and have developed GUI interfaces in the past with it, so I figured it would not be too hard to learn Interface Builder.  It turns out that I was right – it was not too hard, but I could have saved myself a lot of trouble by reading about it a bit more.  All I knew going into it was that it was a GUI based UI designer that can be used to link code to the UI components.

XIB a NIB?
These (.xib and .nib) are the file extensions of an interface file in Xcode.  I got stuck when I could not find the NIB file in my newly created project, because from what little documentation I read, it was supposed to be there.  It turns out that a XIB file is the same thing as a NIB file.  Except that a XIB file is stored on disk as a human readable XML file and a NIB file is stored on disk as a non-human readable binary format.  The reason for this is to facilitate version control of the interface files and ease of comparison with diff tools.  When the project is built, the NIB version is created from the XIB file.  So after learning this fact, I stopped looking for the NIB file (I spent quite some time looking for it).

File’s Owner Proxy Object
When Interface Builder is opened, it opens a window containing four items.  Among them, I would say that the most important to understand is the File’s Owner proxy object.   The File’s Owner proxy object is exactly what its name suggests it is.  It is the owner of the interface file – hence, the [Interface] File’s Owner.   The File’s Owner proxy object loads the interface file when the application launches.   It can also be thought of as the Controller in a (Model-View-Controller) MVC architectural pattern.

Once the File’s Owner proxy object is associated with a controller, you can Connect the object to a View object in the Interface Designer.  I will not go into how to do this here because this article is intended to be more of a high level conceptual one so that you can build a mental schema to flesh out and upon which you can build.  Without the mental framework, it is hard to make sense of new information.

Of course, the View object will have the UI elements like text fields, buttons, labels, and so forth to display on the screen.  Once this is defined, you can use the Interface Builder to Connect or associate each control that is visible on the UI designer to the UI objects defined in your source code, as well as what action it should take once an event is received.

It was actually fairly simple once I had this basic understanding.  Even though I already knew all this before, I still had to get familiar with the new terminologies and design tools to achieve anything useful.  This is the part I dread the most when learning a new language or a tool.  I am not learning anything new or novel conceptually, but I still have to invest the time to learn the tools and platform specific jargons.

In a future article, I intend to write a step by step tutorial with pictures and all that glorious stuff on a simple Cocoa Touch application that will hopefully flesh out the high level conceptual ideas in this article.

By the way, my purpose in writing these articles is an educational one for, not just you, but for me as well.  It was helpful organizing what I learned in an article, and I hope it was helpful for you too.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Development, iPhone Development , , , , , , , ,