views:

224

answers:

2

I have a UIView subclass that has the following in drawRect:

for(int j=0; j<[myArray count]; j++){
    if([myArray objectAtIndex:j]!=@""){    
        [[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1] set];
        CGContextFillRect(context, CGRectMake(55+(20*j),10,15,5));
        [[UIColor blackColor] set];
        [[myArray objectAtIndex:j] drawAtPoint:CGPointMake(55+(20*j),3+) withFont:myFont];
    }
}

I've logged inside the if statement and it works, but for some reason I still get drawn CGContextFillRects at every iteration of the loop, even when my current array object is @"".

I'm fairly new to drawing, so please excuse me if I'm missing something huge and trivial.

+3  A: 

You can't test for equality with == or != when using objects; you need to use -isEqualTo:. For example:

for(int j=0; j<[myArray count]; j++){
    if(![[myArray objectAtIndex:j] isEqualTo: @""]){    
        [[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1] set];
        CGContextFillRect(context, CGRectMake(55+(20*j),10,15,5));
        [[UIColor blackColor] set];
        [[myArray objectAtIndex:j] drawAtPoint:CGPointMake(55+(20*j),3+) withFont:myFont];
    }
}

Each object in your array is a pointer to memory. Even if two objects have the same logical contents (such as an empty string), they most likely point to different chunks of memory. What you want to do is compare the contents of those memory chunks, which is what -isEqualTo: does.

Ben Gottlieb
-[ isEqualToString:] is a more appropriate method for NSString class.
Deepak
Yes, but it wasn't clear that every object in the array was a string.
Ben Gottlieb
`isEqualTo:` is technically for scripting. The actual generic equality method is `isEqual:`. http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Protocols/NSComparisonMethods_Protocol/ http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isEqual:
Peter Hosey
Great answer. Thanks!
Mike A
+1  A: 

if (![[myArray objectAtIndex:j] isEqualToString:@""]) {

Squeegy