Proper coding?

Discussion in 'Mac Programming' started by Spike099, Mar 25, 2007.

  1. macrumors regular

    Joined:
    Feb 18, 2007
    Location:
    Canada
    #1
    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.
     
  2. macrumors 6502

    Joined:
    Mar 31, 2005
    Location:
    London, England
    #2
    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.
     
  3. thread starter macrumors regular

    Joined:
    Feb 18, 2007
    Location:
    Canada
    #3
    Incredible! Thank you so much.
     

Share This Page