Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Displaying the number of likes -- Photo Bombers Extra Credit

Hello, I am having trouble displaying the number of likes in the _usernameButton title. The correct number of likes does however print every time. This is the code that crashes the application somehow:

>  NSString *likes = [_photo valueForKeyPath:@"likes.count"];
>  NSLog(@"Likes: %@", likes);
>  [_likesButton setTitle:likes  forState:UIControlStateNormal];

Here is my full setPhoto:

>  - (void)setPhoto:(NSDictionary *)photo {
_photo = photo;
NSDate *createdAt = [NSDate dateWithTimeIntervalSince1970:[_photo[@"created_time"] doubleValue]];
[self.timeButton setTitle:[createdAt sam_briefTimeInWords] forState:UIControlStateNormal];

NSString *username = [_photo valueForKeyPath:@"caption.from.username"];
[_usernameButton setTitle:username forState:UIControlStateNormal];

NSURL *url = [[NSURL alloc]initWithString:[_photo valueForKeyPath:@"caption.from.profile_picture"]];
NSData *data = [[NSData alloc]initWithContentsOfURL:url];
UIImage *avatar = [[UIImage alloc]initWithData:data];
[_avatarImageView setImage:avatar];

NSString *likes = [_photo valueForKeyPath:@"likes.count"];
NSLog(@"Likes: %@", likes);
[_likesButton setTitle:likes  forState:UIControlStateNormal];

}

Thanks again.

1 Answer

Hi! I think it's because "[_photo valueForKeyPath:@"likes.count"];" returns a NSNumber instead of NSString as you might think.

So try following:

NSNumber *numberOfLikes = [_photo valueForKeyPath:@"likes.count"];
[self.likesButton setTitle:[NSString stringWithFormat:@"%@",numberOfLikes] forState:UIControlStateNormal];

Hope this help!

This worked perfectly, thanks !