【问题标题】:Why does an NSObject have to be initialized before its' .class-property is readable为什么 NSObject 必须在其 .class-property 可读之前进行初始化
【发布时间】:2016-08-21 06:59:14
【问题描述】:

如果我说例如:

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

它将按预期记录UIImageView


现在,如果我改用 UIImageView 的 .class 属性来分配对象(在第 0 行声明/定义为 UIImageView)的方式编写代码,它将记录 (null)

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

即使我在读取它的 .class 值时将对象硬转换为 UIImageView,当我稍后去记录所述类值时,我仍然会得到 (null)

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

【问题讨论】:

  • [[myImageView.class alloc] init][[nil alloc] init] 相同,它什么都不做。
  • 是的,我明白了。我的问题真的是,为什么它是nil,即使我已经将它转换为UIImageView *

标签: ios objective-c uiimageview


【解决方案1】:

因为你还没有初始化你myImageView,你.class返回nil给你。

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

所以如果你想做类似的事情:

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

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

【讨论】:

  • 谢谢,这是为我正在尝试做的事情(涉及 CLANG 快捷方式)设置类的好方法
  • 我不知道NSClassFromString
猜你喜欢
  • 2011-12-08
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多