Replacement for NSLog, DLog

As developers we often require the use of NSLog to print out to console for debugging purposes.
That is totally fine for development purposes. However when we come to releasing the software, we often realize that we have heaps of output going on. When this happens, we then go back and start commenting or deleting the NSLogs.

Well this sounds like quite a pain right? Fear not! Here comes DLog. I add the following in _Prefix.pch

#ifdef DEBUG_PRINT
#define DLog(format, ...) NSLog(@"%s: " format, __FUNCTION__, ##__VA_ARGS__)
#else
#define DLog(format, ...) do {} while(0)
#endif

How you would use it will be the same as the normal NSLog. For example,

DLog(@"hello world! %d", int_variable);

And then, in XCode, click on your project targets, select your app and click on Info to inspect it.
Ensure your configuration is under debug and show is under Settings defined at this level to make things easier.

After that, insert DEBUG_PRINT=1 under Preprocessor Macro.

And voila! when under debug mode, your logs will still show up in the console. However under release mode, the logs will magically disappear! Magik!

Custom Highlight In NSTableView

It’s been a while since I last wrote a post. That’s cause I’ve been rather busy with work. Such is life..

Anyway, I’ve been working with Cocoa and Objective-C quite often now (part of my job) and I’m learning alot as I go along. I decided I shall post up something that took me a while to figure out but it’s actually quite simple to implement, as the title states, custom highlighting in NSTableView (and some custom background).

Custom tableview

Custom tableview


Standard tableview

Standard tableview

It is actually rather simple thanks to the flexibility of Object Oriented Programming. Each row as displayed in the tableview is actually a NSTextFieldCell class. However of course, the NSTextFieldCell is within a NSTableColumn, which is within the NSTableView, which is within a NSScrollView, but anyway.. moving along.

So the class that is responsible for the drawing of each row is NSTextFieldCell, what should we do? We override it to do what we want of course! Without further ado, let’s delve into some code.

//
//  customTextFieldCell.h
//  ControlPanel
//
//  Created by Han on 9/23/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import <Cocoa/Cocoa.h>


@interface customTextFieldCell : NSTextFieldCell {
	NSColor *color;
}

@end

Since I will only be using a simple color for this example, I’m going to add a color class to the NSTextFieldCell so that I may set the color If I want to. You can use a gradient or image if you want to, really.

//
//  customTextFieldCell.m
//  ControlPanel
//
//  Created by Han on 9/23/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "customTextFieldCell.h"

@implementation customTextFieldCell

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
{
	if([self isHighlighted])
		color = [NSColor redColor];
	else
		color = [NSColor greenColor];
	cellFrame.size.width += 5;
	[color set];
	NSRectFill(cellFrame);
	[[self title] drawInRect:cellFrame withAttributes:nil];
}

@end

Next would be the implementation of our custom NSTextFieldCell. The function that is responsible for drawing the look and text of each row is – (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView. The things that are going on inside the class is pretty simple.

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView;

Firstly we check if the cell itself is highlighted via [self isHighlighted], and if we are, we set the color to Red, if we are not, we shall set the color to Green. With this, we get the effect that the normal background of the custom text field cell is green, and if it is selected, it turns red.

	if([self isHighlighted])
		color = [NSColor redColor];
	else
		color = [NSColor greenColor];

After the logic for handling the color, all we have to do is to do a [color set];

	[color set];

to set the color to be displayed.

After which we fill the rectangle of the cell which is passed into the function as a parameter using the function NSRectFill(cellFrame);.

	NSRectFill(cellFrame);

Ok, so now we have the cell beautifully displaying its respective nice green and red colors (Yes I know the color is atrocious..), aren’t we missing something? Yes! The text! right now, we haven’t written the code to draw the text yet! Unfortunately when we override, we handle everything, from the look to the drawing of the text as well. Luckily it’s very simple to draw the text, there is a function from NSString that draws within a given rectangle:

	- (void)drawInRect:(NSRect)aRect withAttributes:(NSDictionary *)attributes

You may read more about it in the documentation.

The text that we set into the cell can be retrieved from the cell using [self title] which tells the cell to retrieve it’s own title.
After which drawing the text into the frame of the cell is easy as…

	[[self title] drawInRect:cellFrame withAttributes:nil];

And voila! We’re done! We now have a custom NSTextFieldCell that can display colors!

Now how do we use it? Lets take a look at the controller class that I wrote to set up the tableview that I dragged and dropped in Interface Builder.

//
//  controller.m
//  custom table view
//
//  Created by Han on 11/4/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "controller.h"
#import "customTextFieldCell.h"

@implementation controller

-(void)awakeFromNib {
	
	NSTableColumn *tableColumn = [[myTableView tableColumns] objectAtIndex:0];
	customTextFieldCell *customHighlights = [[[customTextFieldCell alloc] init] autorelease];
	[tableColumn setDataCell:customHighlights];
	NSSize mySize;
	mySize.width = mySize.height = 0;
	[myTableView setIntercellSpacing:mySize];
	
	list = [[NSArray alloc] initWithObjects:[NSString stringWithString:@"One"], [NSString stringWithString:@"Two"], [NSString stringWithString:@"Three"], nil];

}

-(void)dealloc {
	[super dealloc];
	[list release];
}

#pragma mark -
#pragma mark Tableview Datasource

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView {
	return 3;
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)rowIndex {
	return [list objectAtIndex:rowIndex];
}

- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)row {
	if(row<3)
		return YES;
	else {
		return NO;
	}
	
}


@end

Okay so I’ve hardcoded most stuff just for this tutorial, but you may adapt it to however you want it to work. There is a lot of code in this class, but most of them are for initializing and setting datasource for the NSTableView.

The most important part of the code here to take if is the following:

customTextFieldCell *customHighlights = [[[customTextFieldCell alloc] init] autorelease];
	[tableColumn setDataCell:customHighlights];

These 2 lines of code creates our customTextFieldCell that we wrote, and then set it to the tableColumn that the default textfieldcell is in.
(Alternatively you may manually set the class of the NSTextFieldCell in your Interface Builder to the custom textfield cell that you wrote too)

And we are done!

I hope you find this article useful, do leave feedback if you have any suggestions for improvements or any question. I’m not a pro, but I’ll try to answer any questions.

Four Squares

I was waiting in line for my sushi when my friend posted me the Four Squares question.
Basically you have a square, split into 4 equal quarters. 3 of the quarters are shaded around the center of the main square.
Four squares
The first question posted to me was, how do I split the unshaded space from the quadrant with a coloured center into 2 equal parts?
That was easy, I just drew a diagonal line from the tip of the coloured box to the corner, effectively splitting the unshaded part into 2 equal parts.

The next question was how can I split the whitespace in the next quadrant into 3 equal parts? That was pretty easy, therefore I drew 2 lines at the corner of the coloured square effectively splitting the white space into 3 parts.

The next question that was given to me was, how do I split the last remaining quadrant with a coloured core into 4 equal parts.

I tried splitting it into 12 parts which works! Except that the parts must be equal, which means that they must all be of the same shape and size.

I’ve been pondering the question for the past whole day and I still haven’t found a solution yet.
apparently it’s easy, but I’ll put up my answer up here when I figure it out.

Managing Eclipse IDE

For some reason unknown, I decided to delete the project from my navigation bar on the left and re-add it in again.

My first attempt was using the “File”->”Import”->”Existing Projects into workspace”, whereby I had to select the root folder and the user will be given the choice to choose which project folder to import into the workspace. This can also be used to make a copy of the project from an external folder into the eclipse workspace.

Because my project was already in the workspace, therefore I selected my workspace as the root folder. After scanning through the root folder, the project that I wanted open in navigator wasn’t listed. It had the error “Some projects cannot be imported because they already exist in the workspace”.

This had me puzzled. After much trial and error, I found the solution to be creating a new project and then specifying the new project name as the same as the existing project folder. Eclipse will then search the folder for existing build paths and what not and add it into your navigation panel :)

Hope this helps someone.

Simulation of a Queue with Threading

I had an interesting problem which required me to do a simulation program of people entering a queue and getting served.
So basically, the array of 20 is the Queue or waiting area, and it can only be access by only one process at any one time.

The person with the lowest ID will be served first in the Queue.

After either process is done, it will then sleep for a random time from between 1 to 10 second so as to simulate random people coming in and getting served at random times.

This example uses mutex to protect the shared resource from being written and read at the same time. 0 is used to represent an empty slot in the queue.
the source code should be self explanatory with comment, hope this helps someone.

Enjoy.

Continue reading

How to write a shell in C using fork() and execv()

In this tutorial, we will attempt to write a simple shell in C.

han@han-laptop:~/workspace$ ./myShell
myShell>ls
myShell  myShell.c  task1.cpp  test.txt
myShell>echo "hello I am a shell!"
"hello I am a shell!"
myShell>^C
han@han-laptop:~/workspace$

So let’s break this sequence down to see what components are required to make this work.
Firstly, we would require fork() to spawn a new process. The new process will be an exact copy of the calling process.
Secondly we would require execv() replace the currently executing program with a newly loaded program image.
The syntax for execv would be:

execv(const char *program, char **args);

The first argument to execv() will be a path to the program. So let’s say we want to run ls -al, the path that we want to pass to execv() will be /bin/ls.
The second argument to execv() will be an array of pointers to null-terminated strings that represent the argument list available to the new program.

So some code now:
Continue reading

Singly Linked List

Singly Linked List

So here comes a tutorial for Linked List. There are many types of linked list, a single linked list, doubly linked list etc. For today, I shall explain how a linked list works.

A linked list would require a fixed pointer to know where to start the list. This will be represented in my explanation as  [header]. A node will be represented by a [node], and pointers will be represented as ->.

A basic list looks like this [header]->[node]->[node]->[node]->[node]->NULL

So before we get anywhere, let’s take a look at the basic structure of a list. The main parts of a list, would be the nodes. A node is an allocated piece of memory that can store content, and also has a pointer that can point to another node. So let’s take a look at some code.

Continue reading

Binary Tree and Searching in C

Binary Tree

So here I go, I’ve been a big fan of algorithms and their applications. I shall publish my implementation for a binary tree today. Including functions to traverse(move around) the tree in 3 different orders, mainly pre-order, in-order and post-order. A brief description of what a binary tree is. A binary tree is a data structure whereby the left leaf of the parent node is always smaller than the parent node, and the right leaf of the parent node is always larder than the parent node. So a textual representation of the binary search tree will be something as follows:

7
/    
5           9
/           /  
4         6  8        10

Okay, now I know the figure above won’t look much like a tree due to the formatting, but I tried. You should be able to see the gist of what a binary tree looks like.

Now you might ask what’s the use of having a binary tree?

So how does searching work?

Example: Searching for “8” in a tree.

I start at the first level,  is the node value(7) the value that i’m searching for(8)?  no.

Is “8” > “7”?  yes, therefore I shall move down towards the right, second level.

Is the node value(9) the value i’m searching for(8)? no.

Is “8” > “9”? no, therefore I shall move down towards the left, third level.

Is the node value(8) the value i’m searching for(8)? Yes.

We have now successfully found our value. You might now ask, what if it doesn’t exist? Well if the value doesn’t exist, then it will hit a NULL node, which will then signify the end of the search.

Some code below.

Continue reading

xampplite and symfony

xampplite is a great package which comes packaged with mysql and apache web server. It is extremely easy to install, configure, secure and use. I have been using xampplite for quite sometime now just for development purposes and fun.

Today, I decided to give symfony a go. symfony is a php framework which is very popular. More detailed documentation can be found at http://www.symfony-project.org

Setting it up to use was relatively easy. Since I already had xampplite installed which provides me with a mysql database and apache web server, all I needed to do was to download symfony, unzip it and move it into my development location.

After some going through the Getting Started in the symfony project page, which is relatively simple,  I ran into a problem. Getting symfony requires running certain files using php, eg “php dirdirfilename -V”. When I tried typing “php dirdirfilename -V”, all I got in return was “‘php’ is not recognized as an internal or external command etc etc”. Now, I know php works on my machine, using the shell provided by xampplite and typing in “php -v” produced results. Therefore I was sure i was missing something somewhere. After a quick thought, I remembered that the global variable for php might have not been set. For the various operating systems, go search out how to set the global variables. I’m using windows 7, so all i had to do was to right click on My Computer->Properties->Advanced system settings->Environment Variables.

There should be a “Path” under System Variables. All I had to do was to append “;D:xampplitephp” at the end of the existing line. The semi-colon in the quote that I typed is not a typo error. It is used as a delimiter, therefore to append the location of my php to Path, the semi-colon was required. I had to reboot my computer for it to take effect. (my xampplite folder was in my D drive)

Typing “php -V” in my command line returned the version of php that my box is running, so there, problem solved! :)