Mike A
Mike A

Reputation: 2529

Problem drawing in custom UIView class

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.

Upvotes: 0

Views: 645

Answers (2)

Alex Wayne
Alex Wayne

Reputation: 186984

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

Upvotes: 1

Ben Gottlieb
Ben Gottlieb

Reputation: 85522

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.

Upvotes: 3

Related Questions