Alex Blair
Alex Blair

Reputation: 614

NaN ERROR iOS (NSUInteger vs. CGFloat)

I pulled this code from a reputable tutorial, and I get a NaN error on the CGFloat instance *imageHeight when I run the application. However, if I change the type to NSUInteger, the app builds out just fine. Is there anyone who could potentially explain whats happening. I understand the NaN = Not A Number, but CGFloat should work fine as the data type.

Crashes

CGFloat imageHeight = self.mediaItem.image.size.height / self.mediaItem.image.size.width * CGRectGetWidth(self.contentView.bounds);
self.mediaImageView.frame = CGRectMake(0, 0, CGRectGetWidth(self.contentView.bounds), imageHeight);<--NaN ERROR is thrown here

Does Not Crash

NSUInteger imageHeight = self.mediaItem.image.size.height / self.mediaItem.image.size.width * CGRectGetWidth(self.contentView.bounds);
self.mediaImageView.frame = CGRectMake(0, 0, CGRectGetWidth(self.contentView.bounds), imageHeight);

Full method body

- (void) layoutSubviews {
    [super layoutSubviews];

    NSUInteger imageHeight = self.mediaItem.image.size.height / self.mediaItem.image.size.width * CGRectGetWidth(self.contentView.bounds);
    self.mediaImageView.frame = CGRectMake(0, 0, CGRectGetWidth(self.contentView.bounds), imageHeight);

    CGSize sizeOfUsernameAndCaptionLabel = [self sizeOfString:self.usernameAndCaptionLabel.attributedText];
    self.usernameAndCaptionLabel.frame = CGRectMake(0, CGRectGetMaxY(self.mediaImageView.frame), CGRectGetWidth(self.contentView.bounds), sizeOfUsernameAndCaptionLabel.height);

    CGSize sizeOfCommentLabel = [self sizeOfString:self.commentLabel.attributedText];
    self.commentLabel.frame = CGRectMake(0, CGRectGetMaxY(self.usernameAndCaptionLabel.frame), CGRectGetWidth(self.bounds), sizeOfCommentLabel.height);

    // Hide the line between cells
    self.separatorInset = UIEdgeInsetsMake(0, CGRectGetWidth(self.bounds)/2.0, 0, CGRectGetWidth(self.bounds)/2.0);
}

Upvotes: 0

Views: 1098

Answers (1)

rob mayoff
rob mayoff

Reputation: 385998

The only likely way that you could get a NaN there is by computing 0 / 0, so I deduce that the height and width members of self.mediaItem.image.size are probably both zero. That is, self.mediaImage.image.size is probably CGSizeZero.

Note that if self.mediaItem is nil, or if self.mediaItem.image is nil, then self.mediaItem.image.size returns CGSizeZero. My guess is one of those is nil.

You can easily check this. Either put a breakpoint in layoutSubviews, or add an NSLog at the top of it:

NSLog(@"layoutSubviews: mediaItem=%p image=%p size=%@",
    self.mediaItem, self.mediaItem.image,
    NSStringFromCGSize(self.mediaItem.image.size));

Upvotes: 6

Related Questions