0

Possible Duplicate:
How to convert NSNumber to NSString

Segue to pass string from MainViewController to DetailViewController:

MainViewController.m

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {


    if ([[segue identifier] isEqualToString:@"DetailSegue"]) {

        NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
        DetailViewController *detailViewController = [segue destinationViewController];

//Name:
detailViewController.detailName = [[sortedObjects objectAtIndex:selectedRowIndex.row] valueForKey:@"Name"];

//Attempt with number:
detailViewController.detailPopularity = [[sortedObjects objectAtIndex:selectedRowIndex.row] valueForKey:@"Popularity"];
    }
}

DetailViewController.h

//Name:
@property (nonatomic, strong) IBOutlet UILabel *nameLabel;
@property (nonatomic, strong) NSString *detailName;

//Attempt with number:
@property (nonatomic, strong) IBOutlet UILabel *popularityLabel;
@property (nonatomic, strong) NSString *detailPopularity;

DetailViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];

//Name:    
nameLabel.text = detailName;

//Attempt with number:
popularityLabel.text = detailPopularity;
}

In this example the app crashes because it can't display a NSNumber in UILabel. I need to see an example on how to convert the NSNumber into a NSString so I can display it in a label, I've tried in different ways but I can't find the right combination to fix the error..

Community
  • 1
  • 1
ingenspor
  • 924
  • 2
  • 15
  • 37

3 Answers3

2

in addition to existing answers you can use without any other classes

Label.text = [theNumber stringValue];
aknew
  • 1,101
  • 7
  • 23
1

Use NSStringWithFormat.

popularityLabel.text = [NSString stringWithFormat:"%@", theNumber];

If you want a specific format you can use:

popularityLabel.text = [NSString stringWithFormat:"%.2f", [theNumber doubleValue]];
Hampus Nilsson
  • 6,692
  • 1
  • 25
  • 29
0

I didn't see your NSNumber part, but this should work:

Label.text = [NSString stringWithFormat:@"%f",[YourNSNumber doubleValue]];

You can change doubleValue to whatever you need, could be intValue and so on. And you need to do a bit research to see what kind of format of the string you want when you convert a floating point to a string.

Hope this helps

Raymond Wang
  • 1,484
  • 2
  • 18
  • 33