Tag Archives: objective-C

Suggested Frameworks for iOS

Here are some suggested frameworks for iOS development, since I have used all of them quite a lot. I think they are good frameworks/libraries that you may need to know. It could save you a good amount of time in researching and reinventing the wheel.

List of Frameworks/Code Snippets for Objective-C:

List of some good components

CorePlot : Core Plot is a plotting framework for OS X and iOS. It provides 2D visualization of data, and is tightly integrated with Apple technologies like Core Animation, Core Data, and Cocoa Bindings.

Core Plot Graph

Core Plot Graph

iPhone Cocoa Http Server:

CocoaHTTPServer is a small, lightweight, embeddable HTTP server for Mac OS X or iOS applications.

Sometimes developers need an embedded HTTP server in their app. Perhaps it’s a server application with remote monitoring. Or perhaps it’s a desktop application using HTTP for the communication backend. Or perhaps it’s an iOS app providing over-the-air access to documents. Whatever your reason, CocoaHTTPServer can get the job done. It provides:

 

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

Spaces vs. Tabs

Use only spaces, and indent 2 spaces at a time.
Line Length

Each line of text in your code should try to be at most 80 characters long.
Method Declarations and Definitions

One space should be used between the - or + and the return type, and no spacing in the parameter list except between parameters.
Method Invocations

Method invocations should be formatted much like method declarations. When there’s a choice of formatting styles, follow the convention already used in a given source file.
@public and @private

The @public and @private access modifiers should be indented by 1 space.
Exceptions

Format exceptions with each @ 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.
Protocols

There should not be a space between the type identifier and the name of the protocol encased in angle brackets.
Blocks

Blocks are preferred to the target-selector pattern when creating callbacks, as it makes code easier to read. Code inside blocks should be indented four spaces.

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

Login To Twitter with iPhone

Login To Twitter

Share on Twitter

Share on Twitter

 

 

 

 

 

 

 

 

 

 

 

 

http://amanpages.com/sample-iphone-example-project/multiple-login-for-twitteragent/

Windows Phone 7 v.s iPhone Presentation in Barcampsaigon

Windows Phone 7 and iPhone Presentation

Windows Phone 7 and iPhone Presentation

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:

XCode Code Generation

XCode Code Generation

- 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.

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:

Special Breakpoints in XCode

Special Breakpoints in XCode

 

 

Results of adding Breakpoints to XCode

Results of adding Breakpoints to XCode

 

 

 

 

 

 

 

 

 

 

 

 

Reference:

Hidden XCode build and debug template

Become Productive in Xcode

iPhone App Performance Optimization

iphone performance

iPhone Performance Benchmark

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.

Image Source

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:

How to Reuse a Cell in Interface Builder

Cell Reuse in IB

References:

1/ Web Caching, wikipedia

2/ Web Caching, Stanley Luong’s course material

3/ Stackoverflow – reuseable Cell

4/ Stackoverflow – custom UITableViewCell

Become Master of Xcode

 

Master of XCode

Xcode Master

For iPhone development guys (and Mac as well), we all want to be as productive as possible. And one of our important tools is Xcode. I can even say that if we can master of Xcode, we can double our productivity. The reason is not only the time that the tool can save us but the number of times it breaks our workflow, or make us become bored/tired of our jobs. We are all humans, and no human in the world wants to do the job that a machine can do. Ok, stop talking and I will show you my summary of tips/tricks and techniques that I feel very very useful for me.

Many of these tips is from this stackoverflow post (I just list what I feel is most productive), 2 famous videos called “Becoming productive in XCode”, and a famous cheat sheet that almost all of us know “Complete Xcode Keyboard Shortcut List

I also recommend you to go there and take a look because this post may be really personal and lack excellent tips that you want.

1/ Basic Hot Keys

File Cursor Movement

  • Header/Source File Switching: Option + Command + Up Arrow
  • Last cursor point switch back and forward: Option + Command + Left (Right) Arrow


Quick Help/Documentation

  • Jump to Definition of a symbol : Command + Double-Click on a symbol
  • Find Text in Documentation of a symbol: Option + Double-Click on a symbol: (Only works if you have they symbol’s Doc Set installed.)


Auto Complete

  • (previous) next auto-completion argument : (Shift) + Control + /
  • Auto completion pop-up list : Escape or Control + comma
  • (previous) next Auto completion choices movement: (Shift) + Control + period


Text Movement:

  • Cursor movement between words : Option + Left (Right) Arrow
  • Cursor movement camel-cased parts of a word: Control + Left (Right) Arrow
  • Beginning or end of line: Command + Left (Right) Arrow


Interface Builder:

  • Jump to class in Xcode : Command + Double-click on an object in Interface Builder’s
  • Drag a customized object back to Interface Builder’s Library for later reuse.
  • Object overlap, see object menu under mouse: Control + Shift + Click on an object :


Code Organizing:

  • Bold line in the function list: #pragma mark Foo
  • Auto complete the pragma: pm or #p
  • Notation convention: // TODO: or // FixMe
  • Commenting a line: Command + /


2/ Advanced Hot Keys

With advanced hot keys, you will rarely need to use the mouse. Because, everything you need to do with the mouse, you can do it with the hot keys.

  • Open File Quickly : Command + Shift + D and don’t forget that open quickly uses the current word as a search term.
  • Popup list of methods and symbols in the current file : Control + 2
  • Look up current symbol:  Control + Command + ?
  • Editor area to full screen : Command + Shift + E
  • Debug and Editor Mode switch in All-In-One XCode mode : Command + Shift + B


3/ Some useful scripting

I will tell you more about scripting in the next part, but currently, I think this list is basic enough:

Default Auto Completion list, show when you type

defaults write com.apple.Xcode XCCodeSenseAutoSuggestionStyle List

Turn Off Undo Warning

defaults write com.apple.Xcode XCShowUndoPastSaveWarning NO

Hope that now you can code iPhone app much faster with XCode

Logging class/method/variable name in Objective-C

Just a small post for an effective tip in Objective-C.

Usually if you use the

NSString *name = @"Hello World";
NSLog(@"%@", name);.
Output: Hell world

And usually, when we debug the program and viewing the log, we really want to know the class/method/variable name and line number as well. You can manually hard code it like

NSLog(@"ApplicationDelegate - applicationDidFinishLaunching - name - Helloworld");

But, it is really time consuming and repetitive task. For our company, we use

#define NCLog(s, ...) NSLog(@"<%@:%s:{%d}> %s = %@",
[[NSString stringWithUTF8String:__FILE__] lastPathComponent],
 NSStringFromSelector(_cmd), __LINE__, #__VA_ARGS__ , [NSString stringWithFormat:(s), ##__VA_ARGS__])

Another variant of this is (it combines both class name and method name into __FUNCTION__):

#define NCLog(s, ...) NSLog(@"<%s:{%d}> %s = %@", __FUNCTION__, __LINE__, 
 #__VA_ARGS__, [NSString stringWithFormat:(s), ##__VA_ARGS__])

Then you can just use it like NSLog. For example:

NCLog(@"Hello world");

Output: <ApplicationDelegate:applicationDidFinishLaunching:100> name: Hello World

Good luck to your new productivity:). For your programming language, stop using the System.out.println() and Console.WriteLine, find a version of yourself

References:
Log the method name in objective-C posted in stackoverflow

Print out the variable name in Objective-C posted in stackoverflow