Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Spike099

macrumors regular
Original poster
Feb 18, 2007
143
0
Canada
Hey guys,

I could use some insight in the following code..

Code:
- (IBAction)count:(id)sender
{
	NSString *string = [[NSString alloc] initWithString:[textField stringValue]];
	int i = [string length];
	[labelField setStringValue:[NSString stringWithFormat:@"%@ has %d numbers",string, i]];
	[string release];
}

So... A user types a message in the textField and when he clicks count, labelField shows a message with his original message and tells him the number of characters in the message. Very straight forward ( this is a challenge example from the book cocoa programming for os x that I am going through right now ).

What I'd like to know is if anyone would implement this differently.
 

Nutter

macrumors 6502
Mar 31, 2005
432
0
London, England
You don't need to allocate and initialise a new string, as the -stringValue method returns an autoreleased string that you can use as is.

In fact, you don't need the string variable at all - a good rule of thumb is that variables are for things that vary. ;)

Finally, if this were a real project I would want to use a more descriptive name for the method.

So:

Code:
- (IBAction)updateLabelField:(id)sender
{
	[labelField setStringValue:[NSString stringWithFormat:@"%@ has %d numbers", [textField stringValue], [[textField stringValue] length]]];
}

Less code is better code. The best code is no code.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.