Dec 312008

My application required that the audio be playing and recording at the same time.  In the early phases of development, I ran into a problem where the application would not record while a sound was playing.  If you are running into this problem, I recommend looking up the Audio Session Programming Guide in Apple’s SDK documentation.

If you don’t feel like reading through all that documentation, the simple answer is setting the audio session category to the proper value.  I had it set to kAudioSessionCategory_RecordAudio.  This records audio only and prevents all playblack.   To play back audio and record at the same time, it must be set to kAudioSessionCategory_PlayAndRecord.

Note:  This was using Audio Queue to record and play back sound.

 Posted by at 6:14 am
Dec 292008

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!

 Posted by at 9:18 am
Dec 232008

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!

 Posted by at 11:46 pm
Dec 192008

Yesterday, I debated about whether I should refinance my mortgage.  But there is something that I glossed over.  You have to consider more than just the monthly savings in mortgage payments.  If you have been paying for your house for many years, you have built up valuable equity.  You might have paid down a lot of your interest, and a big chunk of your payment may be going towards your principal.  But when you refinance, you will be resetting your loan, meaning you might end up paying more in interest.

I used these mortgage calculators to do all my calculations.

According to the calculation, by refinancing to a 4.625% 30 years fixed loan from a 5.375% 30 years fixed loan, on which I have already made 56 (4 years and 8 months) payments, I would be paying an additional $5,560.96 more in interest.

However, if I refinance to a 4.625% 15 years fixed loan, I would be saving $135,656.08 in interest!

But, if I stayed at my current interest rate without refinancing and just made extra payments so that I would be done with the payments in 15 years, I would still be saving $114,178.88 in interest.

What does all this mean to me?

In my personal situation, because I might need the money in the future, I will not be refinancing by paying the enormous $10,800 in closing cost.  I could save over $114,000 by simply making extra payments to pay off my debt in 15 years, or I could save over $60,000 by simply making extra payments to pay off my debt in 20 years.  In my circumstance, this is a better option.

Of course, to those whose main goal is reducing the monthly payment, then refinancing at a lower interest rate is a very viable option.

Another thing I forgot to consider is the interest (compounded, mind you) money I would not be collecting on the $10,800 from having to spend that money for the closing cost.  I just opened a CD account at 3.5%.  With $10,800, after 4 years, I would have made $1593.25 in interest.  So you will have to factor in that cost in your break even analysis.

If I can get a loan under %5 with 0 points, that is the time to refinance.

 Posted by at 6:22 am
Dec 182008

This is fresh.  Just a few minutes ago, I got off the phone with a customer representative from a mortgage company.  With all the news about the home interest rates plumetting, I wanted to see if I could reduce my interest points and cut down my monthly payment.

I am currently at 5.375%.  After verifying my information, I was given a new rate of 4.625%, with 2 points.  The closing cost would have been $10,800.  I would have saved around $212 per month on my mortgage.  To recover the closing cost (break even analysis), I would have to stay in my current house for a little over 4 years.

Actually, that’s not too bad.  But $10,800 is a lot of money — money that I might need because I plan on getting married within the next 4 years.  And we all know how much those cost!

But… I do plan on staying here for at least 4 years, so it’s not a bad proposition.   I’ll have to think more about this.

 Posted by at 7:07 am
Dec 172008

Java Vs. Cocoa Framework
I think people have a tendency to get confused when learning a new language due to the difference in terminologies.  Often, we already have a conceptual knowledge of the topic, but the different terminologies confuse us.  Whenever you get confused, just refer back to what you already know.

Delegation Pattern
For example, the Cocoa Framework makes extensive use of the delegation pattern.  This is just a common design pattern and you should not be so hung up on the terminology itself, but rather keep in mind the idea behind it.  You have probably used it countless times in Java.

Where in Java have you used it?  See if this looks familiar.

Student students[] = new Students[3];
students[0] = new Student("John", "Doe");
students[1] = new Student("Cindy", "Barker");
students[2] = new Student("Mandy", "Moore");
Arrays.sort(students, new NameComparator());

In the Java code above, you delegate the work of comparing the names to the class NameComparator.  So NameComparator is a helper class.  This design pattern is pervasive in the Cocoa and Cocoa Touch framework.  What often ends up happening in Cocoa is that a certain task is delegated to a class, and this class conforms to a certain Protocol.

Once again, if you are a Java programmer, you are already very familiar with this.  Just like Java, Objective-C does not allow multiple inheritance, but it does allow you to implement multiple interfaces.  Protocols are what interfaces are in Java.  The only catch is that unlike a Java interface, you do not have to implement each function in the interface.

Delegation and Protocols work together in tandem in the Cocoa Framework.  You delegate something to a class, and that class conforms to a certain protocol.

Once again, this is exactly the same as the Java example above. The NameComparator class conforms to the Comparator interface.

class NameComparator implements Comparator
    public int compare(Object obj1, Object obj2)

Then the work of comparing the two values is delegated to this new class.

It’s really simple, but simple ideas tend to sound confusing in your head when new terminologies are introduced.

 Posted by at 6:43 am
Dec 162008

This may seem like an article from the left field, but with all the recent market turmoil, it’s hard not to be interested in the economy.  I wrote this some time ago for my own reference, and here I share it with everyone.

I was looking into refinancing my house if the interest rate drops any lower.  I’m currently at 5.375% on a 30 years fixed rate, which is pretty low.  If you can go 1% lower, you can save 1,500 per year on a $150,000 loan.

What affects the 15/30 year fixed interest rates isn’t the Federal Reserves lowering interest rates. It is not directly tied, but influenced by it. What directly drives the long term fixed rate is supply and demand — people who want to buy long term bonds because people are scared of risk.  A lot of people demanding long term bonds means increase in demand, so the interest rate goes down for these products.

The difference between a 15 and 30 years mortgage is that a 15 years mortgage will typical have around 0.5% lower interest than a 30 year mortgage. Of course, this means that you will have a higher monthly payment as well. But that does not mean that you can’t pay off your 30 years mortgage in 15 years by paying more than your minimum monthly payment.  It’s just that the minimum required payment per month is lower.

If you are saving 15-20% of your income into a retirement account, then you are a good candidate for a 15 years mortgage.  Another thing to consider is the alternative minimum tax. If you are a married couple making 140-150 per year, or single and making 70-90 per year, the alternative minimum tax kicks in (if you have too many deductions). If you hit this area, they start wiping out your deductions. If you’re not getting the tax benefits, then it might be a good idea to pay off the house sooner.

When you refinance, lenders will offer you the option of paying for a discount. Meaning, they will agree to lower your interest rate if you pay a certain dollar amount up front. Before considering whether it’s worth it, do a break even analysis.

For example, if you have a $200,000 loan and a 30 years fixed loan, and the lender offers you 5.5% interest rate, then that will be $1136 per month payment.  If they offer you 5.25% if you pay $1500 at closing cost, then the monthly payment drops to $1104 per month, which is a $32 per month in saving.  It will take you 47 months (1500/32) to make up that $1500.  So if you know you’ll be living in your house for at least that long, then it’s a good deal.

There are also two types of no-cost refinances. One of them is the fake type, and the other the real one.

The fake ones roll the closing cost into the loan balance. This is not really free because you’ll be paying for it over the life span of your loan. Meaning if your closing cost is $5000, you’ll be paying for it for 30 years, meaning that $5000 can turn into $10,000 to $15000. So stay away from these.

The real ones will usually have a premium on the interest. Typically the interest rate on these will be 0.5% higher. But you do not pay the closing cost. However, there are some fees that you cannot get away from no matter what, such as the prepay items like taxes, reserves, homeowners insurance etc. However, if you’re current on a 6.5% interest and you can refinance to 6%, then you saved 0.5% at no cost to you.

Another thing to consider is escrow. Lenders generally like you to have escrow and might even charge you a premium if you decide to pay your own taxes. But if you have good credit and are responsible about your finances, you’ll probably want to pay it separately and leave that money in an interest earning account and pay the escrow when the tax is due.

It’s a good idea to educate yourself about what’s involved in the closing cost. Some fees can be negotiated, and others can’t. You cannot negotiate 3rd party fees such as title search, appraisal, attorney fees, etc. However you can negotiate fees such as courier fee, express mail fee, administrate fee. There are also garbage or junk fees such as excessive processing fees, documentation fees, underwriting fees, application fees — these you really want to try to avoid.

And request that they provide you with a good faith estimate, and the day before closing, ask for a HUD statement which will show you exactly how much money you need to show up at the closing table so that you are not surprised.

 Posted by at 9:02 am
Dec 152008

The Problem of Memory Management
Mac OS X Leopard introduced garbage collection, however this feature is missing on the iPhone. Therefore, it is still necessary to manage your own memory through what is known as reference counting.

Reference Counting or Retain Count
Reference counting is actually a very simple idea and has been around for a long time. However, it has a tendency to get tedious when a lot of objects and references are involved.

In Objective-C, every object has a retain count (or a reference count). When an object is created, its retain count is 1. When an object is released, its retain count is 0. When the retain count is 0, the object is deallocated and the memory is freed. As you can see, this is a very simple concept.

We can work through a simple example.

[sam alloc];          // sam has retain count of 1
cindy = [sam retain]; // sam has retain count of 2
[sam release];        // sam has retain count of 1

When the code finishes, sam still has a retain count of 1, so the memory will not be freed. This is because cindy is being clingy and not setting sam free. So in order for sam to be free, we need to release sam one more time.

[sam release];      // sam has retain count of 0

But there is a problem. What if you have a function that returns a newly allocated string? Consider the method below.  

- (NSString)getName
   NSString *name;
   name = [[NSString alloc] initWithFormat:@"Robot No. %d", 23];
   return name;

In the method above, name will have a retain count of 1 because of alloc and initWithFormat. And when we call the method (or send a message in Objective-C lingo), the caller would generally do this.

NSString *robotName = [self getName];
[robotName retain];

We retain the value returned by getName because we do not want the object to deallocate before we are done with it. However, this creates a memory leak because the retain count is at 2. We can call [name release]; inside getName right before it returns, but that would cause the retain count to go to 0 and the object would not exist anymore (because it would have been freed).

Meet the NSAutoReleasePool. We can modify the method above to:

- (NSString)getName
   NSString *name;
   name = [[NSString alloc] initWithFormat:@"Robot No. %d", 23];
   [name autorelease];
   return name;

Take note of the line “[name autorelease];“. This line adds this object to the auto release pool. Meaning, the object will not be freed immediately, but rather sometime later in the future. All the objects in the auto release pool are released when the drain message is sent to the auto release pool.

Somewhere near the beginning of your code, you will have the line below.

NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];

When the autorelease message is sent to an object, it is added to this pool. When [pool drain] is called, all the objects in the pool are sent the release message.

The thing to remember is that objects created with alloc, new, copy, mutableCopy or if any function is called that retains the object and increases the retain count, you will have to call a release for each one of those retains.

Any other method will have a retain count of 1, and the object will be added to the auto release pool so you don’t have to worry about those as long as the pool is drained.

Circular Retains
One final note of caution. You must remember to avoid situations where a circular link is created among objects when object A retains object B and object B retains object A. This creates a circular link and creates a retain cycle.

 Posted by at 1:11 pm
Dec 122008

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.

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.

 Posted by at 6:55 am
Dec 092008

If you have read my MacBook Pro review, you will know that I have a single dead pixel near the center of my LCD screen.  It’s nothing to be worked up about, because it’s a single little dead pixel.  It won’t affect my productivity in any way.  It’s only one tiny, little-bitty pixel among the 1,296,000 pixels on the screen.  I won’t even notice that it’s there after a few days of use!

But every time I use the computer, the dead pixel is staring at me and mocking me.  The harder I try to ignore it, the more it stands out.  I’ve tried breathing techniques and even meditation in hopes of perhaps changing my anal-retentive ways and letting the dead pixel rest in peace.  But I just can’t do it!  It’s driving me insane!

I paid $2,500 for every one of the 1,296,000 pixels on the screen.  That’s like close to $520 per pixel.  And damn it, I want every one of them to be in perfect condition!  I demand it!  I paid Apple over a thousand dollar in extra for the quality, luxury and the brand name, and I want all my pixels.

So, I’ve contacted and requested a replacement.  The customer service representative was very helpful and said that I would not be charged a restocking fee because the laptop was defective.  I wonder if they will still honor it when they find out that it’s only one little pixel.

Has anyone had experiences with regarding similar issues?  If so, please let me know!

I will keep everyone posted with updates.

Update: has gotten back to me. wants me to take the MacBook Pro to Apple and get proof that the laptop is defective to warrant an exchange.  Of course, Apple will most likely say that a single dead pixel is within the 3-5 dead pixels tolerance level.  I really don”t like having to deal with all this hassle, so I’ll just keep the laptop.  It was worth a try though.

 Posted by at 8:46 am