Archive for the ‘Objective-C’ Category
Google Objective-C coding standard
I am not sure what coding standard you follow, but I usually follow the Objective-C coding standard of Google for code formatting:
Spacing And Formatting
- or + and the return type, and no spacing in the parameter list except between parameters.@public and @private access modifiers should be indented by 1 space.@ label on its own line and a space between the @ label and the opening brace ({), as well as between the @catch and the caught object declaration.My New Book – 21 years old achievement
21 years old, I got my first book released, I was so excited. Buy it here
Today’s iPhone and iPad apps developers are often running into the need to refine, improve and optimize their apps performances. As more complex apps can be created, it is even more important for developers to deal with this critical issue.
Pro iOS Apps Performance Tuning and Optimization covers many common but difficult problems when tuning and optimizing performance for iPhone and iPad apps and how to resolve these problems efficiently. This book gives you the following:
- Basic knowledge on common problems in iPhone apps
- Advanced knowledge over data structure, algorithms, multithreading, and network data in iPhone apps
- Comparison with problems and solutions for Android and Windows Phone apps
After reading this must-have book, you’ll be ready to make the most of the processing power of the iPhone with your apps performance optimization know-how.
What you’ll learn
- Benchmark your apps using emulators and real device tests
- Increase and optimize UITableView performance in your iOS apps
- Increase your app performance using image and data caching techniques
- Tune your apps using algorithms and data structures
- Improve your parallel data access using multithreading techniques
- Optimize memory usage for increased battery life and better apps performance
- Use native C code to address memory leaks or EXEC_BAD_ACCESS
Installing App with iPhone Configuration Utility
I always have problems finding a good tutorial for my customers whenever I send them the adhoc app for testing, so I write this post to have a basic place for me and everybody else to send to their beta tester/customer without touching to iTunes with the crazy syncing process. This can be good for JailBreak iPhone as well but this is another story.
1/ Download iPhone Configuration Utility.
You can download the iPhone Configuration Utility for Windows here, and for Mac here.
2/ Plugin and find your device
You can find your device easily, and then choose add button as shown in the red box
3/ Select your app
Open Your File Browser and select the file you need, in this case is JobFinder.app
4/ Go back to device and open the Applications Tab
5/ Installing the app in
New Twitter XAuth and Sharing on iPhone
This Twitter sharing library for iPhone has a great User Interface, comparing to my current library for Twitter Sharing, the only problem is that it does not work with new XAuth project. So, I decided to take that UI and merge into my existing codebase for twitter xauth and sharing. The new library allow you to login, share and logout
https://github.com/vodkhang/Twitter-XAuth-and-Sharing
And here is the result. It looks great and really like the UIAlertView in iPhone
http://amanpages.com/sample-iphone-example-project/multiple-login-for-twitteragent/
Windows Phone 7 v.s iPhone Presentation in Barcampsaigon
Here is my presentation with Nghia Dang on the topic comparing the differences between Windows Phone 7 and iPhone Development. I share it here for others who cannot come. Contact me (vodkhang@gmail.com) or Nghia (nghiadang@kms-technology.com) if you have any questions:
Kms-Technology
iPhone Code Generation – Property
This is my new generation script, mainly copied from here with some improvements to meet my needs:
- Change the dealloc to [self.variable release] instead of [self.variable dealloc];
- Change the @outlet variable to check for the “UI” prefix rather than letting it put IBOutlet everywhere or I have to use 2 scripts at the same time.
- Add some of my own into the assign list
The second one is not a perfect solution for IBOutlet but considering that it doesn’t harm much except let some annoying IBOutlet out.
Twitter: XAuth + Sharing

DDSocialDialog for Twitter
Showing a place for logging and sharing a tweet in Twitter with my new library. You now can use XAuth without even understanding about how it works and you also have a nice facebook-style pop up.
For details about XAuth and how to use the XAuth functions, you can follow this link: Aralbalkan’s blog and his feather apps.
For showing a Twitter Pop up Dialog, I appreciate the effort of DDSocialDialog and the quick image is like in the left hand image.
I hope that this will help other iphone developers and me to cut their time and efforts to redo this dialog again and again.
iPhone Http Server – Bug Fix
Recently, I encountered a serious bug in Cocoa Http Server (for iPhone) that took me and my colleagues time to fix it. However, it turned out to be a simple, easy to fix bug.
If you use the sample code (e.g iPhoneHttpServer3.zip) in the google site, you will sooner or later, recognize a bug that if you upload a file B if file A is still uploaded, you get a crash. Another crash case is that you request to a page, turn off the server and turn it on again, and then upload a file into the server, you get a crash.
What’s going on? Why does this server not behave like any other web servers we know? Generally, the bug is due to the fact that some variables are not init in the correct place. The server assumes that whenever you send it a get request, it will init the data for handling the POST request, which is not always correct. Here is the way you can fix it. Or you can just redownload the whole sample code for CocoaHttpServer for iPhone here
In file HTTPConnection.h
@interface HTTPConnection : NSObject
{
// vodkhang
// Added properties
NSInteger dataStartIndex;
NSMutableArray *multipartData;
BOOL postHeaderOK;
}
// vodkhang
// Added methods
- (BOOL)supportsPOST:(NSString *)path withSize:(UInt64)contentLength;
@end
In file HTTPConnection.m
@implementation HTTPConnection : NSObject
/**
* This method is called after the socket has successfully read data from the stream.
* Remember that this method will only be called after the socket reaches a CRLF, or after it's read the proper length.
**/
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData*)data withTag:(long)tag {
. . .
// Find some places look like this
if(expectsUpload)
{
// Reset the total amount of data received for the upload
requestContentLengthReceived = 0;
// Prepare for the upload
[self prepareForBodyWithSize:requestContentLength];
// Start reading the request body
uint bytesToRead = requestContentLength <
POST_CHUNKSIZE ? requestContentLength : POST_CHUNKSIZE;
[asyncSocket readDataToLength:bytesToRead
withTimeout:READ_TIMEOUT tag:HTTP_REQUEST_BODY];
// vodkhang
// Add this line in
[self supportsPOST:@"" withSize:0];
}
else
{
// Now we need to reply to the request
[self replyToHTTPRequest];
}
}
// vodkhang
// Add this method:
/**
* Returns whether or not the server will accept POSTs.
* That is, whether the server will accept uploaded data for the given URI.
**/
- (BOOL)supportsPOST:(NSString *)path withSize:(UInt64)contentLength
{
// NSLog(@"POST:%@", path);
dataStartIndex = 0;
multipartData = [[NSMutableArray alloc] init];
postHeaderOK = FALSE;
return YES;
}
@end
In file MyHTTPConnection.h
// Remove properties dataStartIndex, multipartData and postHeaderOK // Remove method `supportsPOST:(NSString *)path withSize:(UInt64)contentLength;`
In file MyHTTPConnection.m
// Remove method - (BOOL)supportsPOST:(NSString *)path withSize:(UInt64)contentLength;
I hope it works well. If you have any problem, feel free to contact me at : vodkhang@gmail.com
Become Master of XCode (part 2)
I recommend you to have some few experience with XCode before trying to touch some of the techniques here, especially code generation because it may contain subtle bugs and if you are just a newbie, it is not easy to solve. You may also want to take a look at my first part: Become Master of XCode
Many of the techniques are learnt from “Becoming productive in XCode”
3/ Code Generation Scripting
The most common and boring problem that iPhone developers usually have is writing again and again: private instance variable, @property, @synthesize and then dealloc. It is not just boring but also easy to make mistake. Currently, I found that there is a useful way for developers to generate all @property, @synthesize and dealloc based on the instance variable.
Go into User Script, create your own group and script name:
Copy the script from Github (thanks to AllanCraig) and put into. Don’t forget your hot key to trigger the code generation. You may also need to configure the script a little bit to fit your own purpose and coding convention
4/ Code Template (Text Macros)
They have 2 main kinds of code templates: the built in text macros and your text macros:
a/ Default Text Macros:
Xcode already includes lots of text macros like: init, dealloc, fore (for each), fori (normal for loop over array). See a long list in XCode Completion Macros.
Here is the path for the built in Text Macros:
/Developer/Applications/Xcode.app/Contents/PlugIns/TextMacros.xctxtmacro /Content/Resources/
b/ Your own Text Macros:
You can put more Text Macros into Xcode by understanding and writing the Text Macros yourself. The file location for your Text Macros is: ~/Library/Application Support/Developer/Support/Xcode/Specifications
Here are some samples Text Macros that I will work through to get you the feeling of the Text Macros. I hope that after I exlain it, you can create your own.
{
Identifier = objc.dealloc;
BasedOn = objc;
IsMenuItem = YES;
Name = "Dealloc Method Definition";
TextString = "- (void) dealloc$(BlockSeparator){nt<#!deallocations!#>
nt[super dealloc];n}n";
CompletionPrefix = dealloc;
}
Identifier : the id of your method
BasedOn : the programming language of your macro. Here is objc
Name : a descriptive name
Text String: the text string will replace your Macros:
${BlockSeparator} : the way you specify the spaces in your code, you can configure it through terminal and script
<#!deallocations!#> : a placeholder with the text deallocations.
[super dealloc]; : the text appears in your macros
5/ File and Project Templates
You can change your file and project templates, there is not much to say here. You have a built in project and file templates in:
/Developer/Platforms/iphoneOS.platform/Developer/Library/Xcode/Project Templates /Developer/Platforms/iphoneOS.platform/Developer/Library/Xcode/File Templates
But you should create your own file and project templates in:
~/Library/Application Support/Developer/Shared/Xcode/Project Templates ~/Library/Application Support/Developer/Shared/Xcode/File Templates
You may want to copy some from the default templates and modify. The reason that you should put in your own folder is that if Xcode is upgraded, it will not delete your modification
6/ Debugging Techniques
You should also add these 2 breakpoints so that XCode will stop at the crash point when exception happens. You can add breakpoints either via command line:
gdb fb -[NSException raise] fb objc_exception_throw
Or you can also add them using the XCode as shown in stackoverflow
by adding “-[NSException raise]” and “objc_exception_throw” as in the below figure. You should double check the result as well:
Reference:
Hidden XCode build and debug template
iPhone App Performance Optimization
Working in a power limited environment like mobile, and especially, iPhone here, we soon have to face with performance problem in many different kinds. Different than the web model where web front end (javascript) do some (usually not much) processing – also browsers support you a lot, iPhone native application usually has to do quite a lot of processing.
For iPhone native app, you cannot add any hardware to help you to have better performance. The only way you can try to deal is to deal with the software code itself. I will list some few problems and solutions that I figure out these days when I really focus on optimization. The list is applicable somehow to other mobile areas like Android or limited environment like embedded device
1/ Benchmark
It is a really traditional advice, but you always have to remember to benchmark your code, even by using simple tools like NSLog or Instrument tool. You should only care about places that is slow in terms of your test rather than trying guess and error possible places.
2/ Test on iPhone device
This is another traditional advice but people usually forget. You have to test on the real iPhone device. Let me give you an example: on my iPhone simulator, a method runs within 1 second, but in my iPhone device, it takes 8 seconds, a huge difference.
So, when you test your app on the iPhone device, don’t just test for UI, memory or features that the simulator doesn’t have. Remember testing the performance as well.
3/ Multithreading and the main thread
Some people may come to you and tell you that iPhone device just has 1 core and you never need to care about multithreading. It is just WRONG. You still need to do a lot of multithreading to reach a better level of performance.
The main thread will do the user touch event handler and view rendering. Then, if you use the main thread for some calculation that takes a lot of time then your UI just become frozen or not smooth when you scroll.
For UI like UITableView where users scroll between many cells, the runtime will run a loop over visible cells and set the contents. Because this process runs in a row not concurrently, and it will not allow you to view or scroll the UITableView until it returns all cells, you can possibly let some of the cell content run on another thread. (more about performance on UITableViewCell part).
The other reasons for using thread are well-known, heavy IO and network processing, all of them block processing and you need thread so that your main thread is not block. This will help to make users feel your app run with higher performance
But, be CAREFUL, Multithreading comes with its own disadvantages. For rendering the view, you should do it on the main thread or somtimes, your app will just crash randomly. Another traditional reason is that the CPU has to switch too much between threads and it takes more time than usual to finish a task
4/ Use Memory wisely
Some questions on stackoverflow that I sometimes see shows a scare feeling about memory. It is right that iPhone has limited memory but it doesn’t necessarily mean that you should use it as least as you can. Memory and Performance is always a trade-off problem, you must use it smartly
The right mind you need to keep is using that limited memory smartly. We all know the priority of speed is Memory > File and Local IO > Network, the fastest access is always using memory cache for the data. There are some problems for memory caching in iPhone:
- – You have to respond to 1 method in every UIViewController: (void)didReceiveMemoryWarning. In this method, you have to smartly release some memory cache of data to reduce your memory usage.- Know what/when to cache something in memory. There are lots of Caching algorithms outside from simplest ones like: Random Replacement, Least Recently Used, Most Recently Used. It is also an issue of caching big images or caching lots of small images. It all depends on your app. For my app, my main view contains lots of thumbnail images that need displaying fast and the user can wait for seeing big images. So, we cache a lot of images (60-100) for just 2 MB of memory. Knowing how to balance memory usage and good performance will help you a lot
5/ Algorithms and Data Structure
For my case, I didn’t really need to solve big performance issue with Algorithm and Data Structure, but in a limited environment, a small mistake may lead to a big deal and hard to detect. My case was that I need to merge 2 data arrays from the network using some unique characteristics of elements.
The app works really well in the Simulator for about 50-100 for each array (less than 0.5 second) . However, when I tested on the device, the time surprised me, 8 seconds (16 times slower). It cost me 1 hour to detect that I use 2 for loops through 2 arrays which means O(n2), and then, I changed it to a dictionary which reduced the algorithm to O(n) and took me back to 1 second. Phew! Finally, performance is up now
What I learnt here is that even we don’t ever need to deal with Massive Data, we still need to be careful about some algorithm and data structure. 50 elements are nothing in a desktop or server scale but can cause a huge issue on limited environments in iPhone. Another lesson is a remind for me that I should always test on the real device to get the real performance
6/ Reuse UITableViewCell to improve Scrolling Performance
This part is quite unique for iPhone but may be good for other people to learn. In iPhone, we have a concept of UITableView for displaying a list and a table can contain a lot of cell.
The problem is that rendering the Cell (or generally the UIView), takes lots of time and can cause the app to look like stuck when it is scrolling. Usually, if you use the default UITableViewController template, the template already gives you the code for reusing the UITableViewCell.
The only problem is when you create a custom UITableViewCell using some usual tutorials like this and this (especially using Interface Builder), they forget to tell you that setting a CellIdentifer in the UITableView is not enough to reuse a cell. What you need to do is to set it in InterfaceBuilder or write a method to return it. I know that many people will forget it and think that they still reuse the cell, but they don’t. I suffer the same problem until I did benchmark and found the problem recently.
Here are 2 good techniques:
Copied from Stackoverflow, this question:
1st way: Just implement a method with the appropriate method signature:
- (NSString *) reuseIdentifier {
return @"myIdentifier";
}
2nd way:

Cell Reuse in IB
References:
2/ Web Caching, Stanley Luong’s course material
3/ Stackoverflow – reuseable Cell
4/ Stackoverflow – custom UITableViewCell











