gpt4 book ai didi

ios - 不兼容的指针类型用类型为“BaseClass *”的表达式初始化 'SubClass *__strong'

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:48:53 25 4
gpt4 key购买 nike

在 objective-C 中,为什么我们不能 alloc+initnew 具有父类(super class)的基类对象,而我们可以使用父类(super class)的构造函数来初始化吗?

下面是一些代码:

s1 可以很轻松地创建。

NSMutableString *s1=[NSString string];
NSLog(@"%@",s1);

但是s2s3不能,并给出警告

使用类型为“BaseClass *”的表达式初始化“SubClass *__strong”的不兼容指针类型

NSMutableString *s2=[[NSString alloc] init];
NSLog(@"%@",s2);

NSMutableString *s3=[NSString new];
NSLog(@"%@",s3);

//here no warning.
id mem=[NSString alloc];
NSMutableString *s4=[mem init];
NSLog(@"%@",s4);

当我们将 alloc + init 分解为两个不同的语句时会发生什么?

最佳答案

答案可以在Objective-C Features中找到Clang 3.3 文档:

Related result types

According to Cocoa conventions, Objective-C methods with certain names (“init”, “alloc”, etc.) always return objects that are an instance of the receiving class’s type. Such methods are said to have a “related result type”, meaning that a message send to one of these methods will have the same static type as an instance of the receiver class.

因此在

NSMutableString *s2 = [[NSString alloc] init];

右侧的类型实际上是 NSString * 而不是 id,将其分配给 NSMutableString * 会给出“不兼容指针类型”警告。

另一方面,

中的 string方法
NSMutableString *s1 = [NSString string];

没有“相关结果类型”,所以它只返回一个 id 可以分配给 NSMutableString *

只有当您使用 id 作为中间类型时,将 alloc/init 分成单独的语句才能抑制警告。使用 NSStringNSMutableString 你仍然会收到警告:

NSString *tmp4 = [NSString alloc];
NSMutableString *s4 = [tmp4 init]; // <-- Warning here

NSMutableString *tmp5 = [NSString alloc]; // <-- Warning here
NSMutableString *s5 = [tmp5 init];

根据文档,如果方法的返回类型与其类的类型兼容并且如果:

  • 第一个词是“alloc”或“new”,方法是类方法,或者
  • 第一个词是“autorelease”、“init”、“retain”或“self”,方法是实例方法。

关于ios - 不兼容的指针类型用类型为“BaseClass *”的表达式初始化 'SubClass *__strong',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15249505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com