Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting an NSObject to NSString

Tags:

objective-c

I am working through the Stanford iPhone class and I can't figure out why I am getting a compiler warning. I assume I need to cast my object to NSString, but I get an error when I try to do so. The code runs and gives me the expected output, but the warning bothers me.

NSLog(@"lowerCaseString is: %@", [object lowercaseString]);

This runs with the warning: 'NSObject' may not respond to '-lowerCaseString'

NSLog(@"lowerCaseString is: %@", [(NSString)object lowercaseString]);

This throws an error: conversion to non-scalar type requested

like image 529
Joel Hooks Avatar asked Apr 06 '09 04:04

Joel Hooks


2 Answers

I believe this will do what you need:

NSLog(@"lowerCaseString is: %@", [(NSString *)object lowercaseString]);

Note I just added a * to your second line of code to make a pointer to NSString.

like image 167
Adam Alexander Avatar answered Oct 02 '22 20:10

Adam Alexander


Why is object declared as an NSObject if it's supposed to be an NSString? If you intend to call NSString methods on it, declare it as an NSString or leave it as an id. Then you won't get errors.

like image 36
Chuck Avatar answered Oct 02 '22 21:10

Chuck