Search code examples
iosuitableviewnstimezone

How to get TimeZone abbreviation


I want to create a list of time zones. But I got the following error at timeZone.abbreviation.

-[__NSCFString abbreviation]: unrecognized selector sent to instance 0x19cb80b0

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    // Configure the cell...
    NSTimeZone *timeZone = [[NSTimeZone knownTimeZoneNames] objectAtIndex:indexPath.row];
    cell.textLabel.text = timeZone.abbreviation;  // <- Error Here
    cell.detailTextLabel.text = timeZone.description;
    cell.accessoryType = (timeZone == self.timeZone)? UITableViewCellAccessoryCheckmark :UITableViewCellAccessoryNone;

    return cell;
}

I tried to search on the internet but I cannot find the solution so far. Please give me some advice. Thanks in advance.


Solution

  • Try something like this:

    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:[[NSTimeZone knownTimeZoneNames] objectAtIndex:indexPath.row]];
    cell.textLabel.text = timeZone.abbreviation;  // <- Error Here
    cell.detailTextLabel.text = timeZone.description;
    

    Your current code gets an array of NSStrings, not NSTimeZones. This should give you an NSTimeZone, and then you can get the abbreviation property on it.