Albert Renshaw Albert Renshaw - 3 months ago 7
Objective-C Question

Why does an NSObject have to be initialized before its' .class-property is readable

If I say for example:

UIImageView *imageView;
imageView = [[UIImageView alloc] init];
NSLog(@"%@", imageView.class);


It will log
UIImageView
as expected.




Now, if I instead write the code in a way where the UIImageView's
.class
property is used in allocating the object (which is declared/defined as a UIImageView on line 0), it will log
(null)


UIImageView *myImageView;
myImageView = [[myImageView.class alloc] init];
NSLog(@"%@", myImageView.class);//logs (null)





Even if I hard cast the object to a UIImageView whilst reading its'
.class
value, when I then go to log said class value later on, I still get
(null)


UIImageView *myImageView;
myImageView = [[((UIImageView *)myImageView).class alloc] init];
NSLog(@"%@", myImageView.class);//logs (null)

Answer

as you didn't initialize you myImageView yet , you the .class return nil to you.

UIImageView *myImageView;
myImageView = [[myImageView.class alloc] init]; // didn't initialize myImageView
NSLog(@"%@", myImageView.class);//logs (null)

so if you want do Something Like that :

myImageView = [[NSClassFromString(@"UIImage") alloc] init];

NSLog(@"%@", myImageView.class);//logs (UIImage)