Why can't we use dot notation on id when there could be regular syntax?

MyClass.h

@interface MyClass : NSObject

@property (nonatomic) NSString *something;

@end

      

MyClass.m

@implementation MyClass

@end

      

Then I do this:

    MyClass *instance = [[MyClass alloc] init];
    id theSame = instance;

    [theSame setSomething:@"hh"];   // No error
    theSame.something = @"hh";    // "Property 'something' not found…"

      

Why does the fourth line give an error but not the third? They do the same.

+3


source to share


1 answer


There are several discussions around it, and especially programmers who have been around prior to the declared properties will advise against using the dot synthax. However, like any other language, Obective-C has evolved and I think it was in the right direction. Now, to answer your question, you can think of dot syntax as a way to access property. id has no declared properties, so trying to access it will result in a compile-time error. On the other hand, when you use the synthax method, think of it as sending a message to the recipient that is evaluated at runtime. So, by sending any message to id at compile time, the compiler assumes that you know what you are doing and that the recipient will handle the message in some way at runtime. Thus,you can take advantage of this difference: use dot notation all the time, but use the synthax method when you know for sure that the recipient can process the message, but the compiler doesn't know. (these situations are somehow rare, but very important, they allow the use of Objective-C dynamics)



+1


source







All Articles