Saturday, May 29, 2010

Code Syntax Highlighting

notesI have a blog posting on this issue last year. I have really enjoyed to practice those steps to highlight my codes in blog. There are two issues I still don't feel good: first, the HTML codes generated from VIM are not-CSS. The embedded color styles make my blog HTML hard to read and edit. The size of my blog is much bigger even it is not a big deal.

The second issue is that I like change my code background color to black so that it is easy and comfortable for eyes. The white background color is too bright and contrast. It consumes more energy, I think, for the terminal as well. So I think it is time to make change to my code syntax highlighting HTML codes.

Fortunately, I found that VIM has an option for TOhtml command to convert to HTML with CSS classes. The command is very simple:

:let html_use_css=1

The result of TOhtml will be HTML with style css classes defined in header part and all the syntax highlight HTML codes are based on span with class.



The next step is that I have to update my style css classes in my blogger. Two groups of css classes I have to include in my blog header section. It is easy to do since Blogger provides Edit HTML in blog settings. The first group is css classes in my div section as a box for codes. Based on the previous div, I added additional divs with additional background color and text color settings:

...
color: #cccccc;
background-color: #000000;
...

The second group of css files are those generated by VIM in HTML header section. I think VIM use generic css class names for codes. For example, the following are some generated by TOhtml command for Objective-C code:

<style type="text/css">
<!--
.Comment { color: #80a0ff; }
.Statement { color: #fbf204; }
.Special { color: #fb8000; }
.Identifier { color: #40ffff; }
.Type { color: #60ff60; }


For C#, SQL or other languages, the syntax color scheme may be different, but the class names are almost the same. That's the advantage of css.

With above changes, now my codes are and will be in new syntax highlighted colors, and my blog will be much easy to read and maintain.

Read More...

Sunday, May 23, 2010

MyLogger Class in Objective-C (1)

Objective-C is new for me. In the past weeks, I have been working on my first iPhone application. This has been quite interesting and rewarding experience. Since I have been doing development in in .Net for many years, I always compare Objective-C to .Net, or try to find out something similar in Objective-C like ones I have used in .Net. Recently, I found some classes in System.Diagnostics namespace are quite useful, especially Debug class. I can use it to print debug information in my classes and I can use indent feature to net messages in a nice indented structure. All the debug strings are displayed in Visual Studio's output panel. I don't not need to worry about all those debug print codes since in the released mode, they will not work.

In Xcode, there is similar feature available. It is NSLog(), which is a Cocoa foundation function.


This function can be used to print out debug messages in the same way as Debug.Print() in .Net. However, NSLog() is only a C-like function, therefore, there is no other features you can alter the behaviour of its output, as far I know about it. Therefore, I need a wrapper class for NSLog().

I found a very nice blog by Objectuser: A Single Class Logger in Objective C. This is very close to what I want, except for indention. Based on the class, I created my logger class: MyLogger. Here is the header of the class:

#define kLogLevelDebug 1
#define kLogLevelWarning 2
#define kLogLevelError 3
#define kLogLevelInfo 4
#define kLogLevelNone 100

@interface MyLogger : NSObject {
  int mLevel;
  NSString* mContext;
}

@property (nonatomic, assign) int level;
@property (nonatomic, retain) NSString* context;

+ (char) indentChar;
+ (void) setIndentChar:(char)aChar;
+ (NSString*) format;
+ (void) setFormat:(NSString*)aFormat;
+ (int) defaultLoggingLevel;
+ (void) setDefaultLoggingLevel:(int)defaultLevel;

- (id) initWithContext:(NSString*)loggingContext;
- (id) initWithContext:(NSString*)loggingContext logLevel:(int)intentLoggingLevel;
- (BOOL) levelEnabled:(int) intentLevel;
- (BOOL) debugEnabled;
- (BOOL) warningEnabled;
- (BOOL) errorEnabled;
- (BOOL) infoEnabled;
- (MyLogger*) indent:(BOOL)indent;
- (MyLogger*) debug:(NSString*)messageFormat, ...;
- (MyLogger*) warning:(NSString*)messageFormat, ...;
- (MyLogger*) error:(NSString*)messageFormat, ...;
- (MyLogger*) info:(NSString*)messageFormat, ...;
@end

The header file describes all the class members, properties, and methods.

Usage

The main purpose of this class is for easy to use. Typically, you need to create an instance of MyLogger in a class's init(). Then the instance is ready to use. For example, here is a view controller class .h:

@class MyLogger;

@interface MyViewController : UITableViewController
  ...
  @private
    MyLogger* mLogger;
}
...
@end

Notice that the class level mLogger is a private variable. There is no reason for outside to access to this mLogger instance. The following is an exmaple how this mLogger is used in the .m class:

#import "MyViewController.h"
#import "MyLogger.h"
...
@implementation MyViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
   if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
     // create logger with class name as context
     logger = [[MyLogger alloc] initWithContext:@"MyViewController"];
     // log a message and then indent
     [[logger info:@"initWithNibName:bundle:"] indent:YES];
     ...
     [logger info:@"object: %@", obj];

     ...
     // off indent and print msg
     [[logger indent:NO] info:@"initWithNibName:bundle: DONE"];
   }
}
...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [[mLogger debug:@"tableView:cellForRowAtIndexPath:"] indent:YES];
    [mLogger debug:@"indexPath: %@", indexPath];

    ...
    [[mLogger indent:NO] @"tableView:cellForRowAtIndexPath: DONE"];
}
...
- (void)dealloc {
  if ([logger retainCount] > 0 ) {
    [logger release];
  }
  ...
}
@end

I think it is very straightforward: creating logger in init and retain it, using it anywhere in the class, and releasing it at end of the class. I declare logger in the .m file to keep it as private data members in the class. Three is no need to let outside to access or set this instance.

Here is an example output:

[INFO] MyController - viewDidLoad
--[INFO] MyViewController - fetchedResultsController
----[INFO] MyViewController - managedObjectContext
------[INFO] MyViewController - creating new managedObjectContext
----[INFO] MyViewController - managedObjectContext DONE
----[INFO] MyViewController - getFetchRequestWithEntity:inContext:inContext:
----[INFO] MyViewController - getFetchRequestWithEntity:inContext:inContext: DONE
----[INFO] MyViewController - managedObjectContext
----[INFO] MyViewController - managedObjectContext DONE
--[INFO] MyViewController - fetchedResultsController DONE
[INFO] MyViewController - viewDidLoad DONE

My next blog will discuss some key points in MyLogger class.

Reference


Read More...

Tuesday, May 11, 2010

Customize Xcode like MSVS

After month time coding in Xcode, I think I should spend some time to learn Xcode and configurations so that I will be familiar with Xcode short-cut keys. Furthermore, I'll be able to configure my Xcode like Microsoft Visual Studio since I have done more than ten years .Net programming; at least, find out similar ways I use VS.

Key Bindings

This blog provides very useful information about how to customize key bindings. The basic idea is to create a customized .dict file:

/Users/USERNAME/Library/KeyBindings/DefaultKeyBinding.dict

The content of this file is JSON like:

/* ~/Library/KeyBindings/DefaultKeyBinding.dict */
{
"KEY1" = "ACTION1"; /* Bind KEY1 to ACTION1 */
"KEY2" = "ACTION2"; /* Bind KEY2 to ACTION2 */
...
}

The blog list all the modification keys and actions.

This blog has a MSVC key bindings. I gave it a try, but I think I still like to use Xcode default kyes. I like VS smart list or code completion by Control+Space the most. In Mac, I found out that the default Xcode key is "Control+,", F5 or Option+esc. Mac Developer Tips >> Xcode code completion has detail description about this my favorite feature and more.

In the Xcode preference->Key Bindings, a list of actions and keys are defined there. I think the above default keys may fill the blanks when I create a new one as its instructions.

Copy and Paste

The basic copy and paste in Mac is very similar to Windows. For example, Command+C, X, and V for copy, cut and paste, and +Z for undo. I think Control+Y is for redo, but Command+Shift+Z is for redo(I think it make sense in Mac).

In Windows, you can select a text and drag it anywhere, or hold Control key to make a copy. In Mac, the copy is by holding Option key.

Selection Indent

This tip explains how to do selection indent and un-indent. The keys are Command+] or [ for block indent or un-indent.

Block Comment/Un-comment

To comment or uncomment a block of codes, use key Command+/. Repeat to uncomment. This tip (one out of 10) is from the tip by John Muchow.

Refactor

VS provides great set of Rectoring tools, renaming variable is a great one. Xcode also provide this feature. Select a variable and press Shift+Comman+J, a dialog window is displayed. Rename is in a selection on the top left. This article has detail description and picture to show what Refactor is.

Overall, all above pretty much codes most part of features and functions I have used in VS. Xcode is a very competitive development tool for Mac and iPhone application development. I think with my continuing exploring and efforts, I'll be able to find out more powerful features to increase my productivity.

Read More...

Sunday, May 09, 2010

Ouch! iPhone Memory Management

Here is my story about iPhone development update. I thought I had very good understanding of iPhone memory management. For each object created by alloc and init, a corresponding release should be made to balance its life cycle. It is simple, right? When I put my hands on my first application codes, I got hurt! But it was a good experience. Here is the story.

In my codes, one of view controller uses core data as data source. In the header file, a fetchedResultController is defined:

@interface MyViewController : UITableViewController <NSFetchedResultsControllerDelegate, UITableViewDelegate>
{
  // ...
  NSFetchedResultsController *fetchedResultsController;
  // ...
}

// ...
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
// ...
@end


In my .m file, the implementation of my customized getter is like this:

@synthatic fetchedResultsController;
// ...
- (NSFetchedResultsController *)fetchedResultsController {
  if (fetchedResultsController != nil) {
    return fetchedResultsController;
  }
....
  NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc]
  initWithFetchRequest:fetchRequest
  managedObjectContext:managedObjectContext
  sectionNameKeyPath:nil cacheName:@"Root"];
  aFetchedResultsController.delegate = self;
  fetchedResultsController = aFetchedResultsController;
  // [fetchedResultsController retain]; I missed this line to contain the object
  // ...
  return fetchedResultsController;}


My intension to implement getter is for this view controller class to have its own fetched result controller with the class own managed context object and fetch request. However, I did not retain the controller. The result is unexpected with the alloc and init object.

Here is a simplified example:

  instance = aInstance;
  self.instance = aInstance;



The first line is directly reference or pointer assignment. The result is that both variables are pointing to the same memory address, and both variables have the same reference count; while the second line actually calls to the setter property of instance, and the reference of right side variable is passed to the setter method. It will be up to the setter class to retain, copy or do assignment.

In my customized property getter, in order to retain my alloc and init object, there are two options. First option is to do the direct assignment and then to retain it so that object reference count is increased to 1. The second and simple option is call the setter to do it [self instance] = ... The synthetic property definition guards the "retain" feature.

I had spent almost one week of evenings and one week end time to figure the issue out. The exception I got was "EXC_BAD_ACCESS". The following is my NSLog message in the getter method with system crash messages:

2010-04-12 07:15:23.347 MyApplication[8030:207] ... 
2010-04-12 07:15:23.348 MyApplication[8030:207] MyViewController->fetchedResultsController
Program received signal: "EXC_BAD_ACCESS".

The exception happened at the end of the property getter. Now I understand the meaning of "EXC_BAD_ACCESS", at least this is one of many cases. It does say what it means: access to the memory which was released and not accessible.

Actually, I found the clue when I tried to google the issue. When I read some answers about one StackOverflow question (http://stackoverflow.com/questions/327082/exc-bad-access-signal-received). I immediately realized it was memory issue and then realized the object I tried to return was actually released.

It is a really good lesson. iPhone development is new for me, and I really en joy it when I figure out something. This is a way to gain knowledge and to make progress. After I corrected my codes, my application was back to alive and the view was displayed!

Read More...

Saturday, May 01, 2010

Web Tool: EverNote

toolsI think I knew EverNote for a quite while. I heard about it from Stanford University's iPhone training program. EverNote staff gave a special presentation about its free iPhone program and their experience with iPhone application development.

EverNote basically provides a web service to people to make notes about anything, simple text notes, html formatted notes with formatted text, links, pictures, movies. The basic service allows 100 notebooks and 40MB monthly uploading. Nootbooks and tags are great feature to organize notes.

Recently I decided to create my basic account at EverNote. The main reason I like to use this web service to take my personal notes. I can use it anywhere: write, edit and view your notes. To write a blog, normally it takes much longer time than just writing a note. I do my blog most time at weekends. With EverNotes, I can create my notes quickly, anywhere and anytime. It is a great place to record my ideas and findings.

Another great feature is that EverNotes provides RSS feeds for public shared notebooks. For example, here is my .Net notebook RSS feed. This provides a way to share my ideas with my friends and other developers.

Just found that EverNote Mac application has Import and Export features. I just exported all my notes to my Mac. The exported file is an XML file(enex). This provides a back way to import and export notes.

Another similar web service is UberNote, which was created by a group of university students. It was created by the idea to share student's notes. Now it is a public project and it is free. However, it does not support multiple notebooks.

Read More...