0

Can you just tell me why this ...... compiler does not alert me about a possible type mismatch here ?

NSHour* H1; // My object

if (H1 == nil) doSomething
else H1 = [NSString stringWithFormat:@"%@%@", H1, @":00"];  --- Here : affecting an NSString* to an NSHour*
smorgan
  • 20,228
  • 3
  • 47
  • 55
Oliver
  • 23,072
  • 33
  • 138
  • 230

1 Answers1

1

Because the declaration says it returns id:

+ (id)stringWithFormat:(NSString *)format, ...

And id can easily be assigned to anything.

Eiko
  • 25,601
  • 15
  • 56
  • 71
  • Apple has really done bad things with Cocoa. How could this class return anything else than a NSString ? I have to read my whole code because of such stupid declarations... Do you know a Way to override this function to make it return a NSString ? Like a redeclaration ? – Oliver Jan 15 '11 at 23:39
  • No idea if this is possible - and I wouldn't mess with it. But if you have to read a lot of code to spot those things, this is a hint for bad code. Maybe the name of the variables are just to meaningless (H1 certainly is, and it also violates naming conventions). And I don't have any idea why this is typed as *id*... – Eiko Jan 15 '11 at 23:44
  • not necesserely a sign of bad code. Sure I could do best here form naming the vars, but correct var names wouldn't change the fact that I'll have to read my whole code to check where strings are set into other objects without warning. I tried this : http://stackoverflow.com/questions/4702871/iphone-category-on-nsstring-to-make-stringwithformat-return-a-nsstring to prevent the problem. Could you have an eye on this question ? – Oliver Jan 15 '11 at 23:53
  • 1
    @Oliver: read about **categories** in Objective-C. I seem to recall that they allow you to add methods to classes, even those that you don't directly control. Of course this *might* make your code harder to understand, but it's up to you to decide. – s.m. Jan 15 '11 at 23:53