NSValueTransformer Converting BOOL to NSString

Discussion in 'Mac Programming' started by stadidas, Jan 7, 2009.

  1. stadidas macrumors regular

    Joined:
    Feb 27, 2006
    Location:
    Kent, United Kingdom
    #1
    I wanted to create a value transformer that would convert a BOOL value to either a Yes or No string, for displaying data using bindings. However, the method that must be overriden in a NSValueTransformer subclass, - (id)transformedValue:(id)value, expects an object to be passed in. As I am passing in a boolean, the only way I have found that works is this:

    Code:
    - (id)transformedValue:(id)value
    {
    	if ((int)value == 16866128)
    	{
    		return @"Yes";
    	}
    	return @"No";
    }
    
    However, this is obviously really hacky, and also makes the NSTextField subviews that are bound to the value with the transformer applied redraw in a strange way.

    I'm sure there must be a better way of converting booleans to text, does anyone have any pointers?
     
  2. toddburch macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #2
    I'm still learning the language, but figured I'd add to the discussion...

    My understanding is that BOOL isn't a class, but a special type handled by the preprocessor. So, isn't passing it under the (id) umbrella in variable "value" incorrect?
     
  3. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #3
    id is going to be an NSObject subclass, and most likely for your situation it'll be a BOOL inside an NSNumber. So try something along the lines of:

    Code:
    - (id)transformedValue:(id)value {
        if ([value boolValue])
        {
            return @"Yes";
        }
        return @"No";
    }
    Edit: what you're doing in your code is comparing the pointer address, and the reason I'm guessing that it works is because when you create an NSNumber via numberWithBool:, NSNumber internally will cache that object for YES and for NO and always use the same one.
     
  4. stadidas thread starter macrumors regular

    Joined:
    Feb 27, 2006
    Location:
    Kent, United Kingdom
    #4
    I am aware of this; this is why I wanted to find a correct way of achieving what I wanted.

    Ah, interesting, thanks Kainjow. Your method also worked. I should have thought of this myself, but it was late and I'd been coding for hours. Honest :)
     
  5. toddburch macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #5
    I was going in the right direction, as shown by kainjow.

    I was going to suggest something like this, but then realized BOOL wasn't a class...
    Code:
    -(id) transformedValue: (id) value { 
       if (value isKindOf: [BOOL class]) { 
          if (value==YES) return @"Yes" ; 
          return @"No" ; 
       }
       return super(value) ; 
    }
    
    But then I realized that [BOOL class] would have failed.
     

Share This Page