【问题标题】:Incompatible pointer type assigning to 'ViewController'分配给“ViewController”的指针类型不兼容
【发布时间】:2012-04-25 06:56:41
【问题描述】:

我有一个 ViewController 类(也许我不应该这样命名那个类?)

为什么会有警告

分配给“ViewController”的指针类型不兼容 AppDelegate 中的“UIViewController”

更新:

在这一行

self.viewController = [[[myPlugin alloc] getPluginViewController] autorelease];

在 AppDelegate.h 我有

@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@end

在我的插件中

-(ViewController*) getPluginViewController {
self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    return self.viewController;

在 ViewController 我有

@interface ViewController : UIViewController {

【问题讨论】:

  • 不,你不应该为这个类命名。
  • 你在哪里定义了viewController作为属性,你可以添加那个代码吗?
  • 否则,如果您想删除此警告,则可以解决 - self.viewController = (ViewController *) [[[myPlugin alloc] getPluginViewController] autorelease];
  • 可以添加 ViewController 类的定义吗?

标签: iphone objective-c ios uiviewcontroller incompatibility


【解决方案1】:

您的应用程序委托中的 viewController 属性可能具有 UIViewController* 类型,并且您正在尝试为其分配 ViewController* 类型的对象。可能您的 ViewController 类需要从 UIViewController 继承。

您的代码还有很多其他问题:

self.viewController = [[[myPlugin alloc] getPluginViewController] autorelease];

忽略分配,按照惯例,在分配对象后直接发送给对象的第一条消息应该是初始化消息。 99.99% 的程序员会自动认为这是你代码中的一个可怕的错误,无论它是否是一个可怕的错误。你应该遵守约定。

此外,如果getPluginViewController 遵守内存管理规则,则您不拥有它返回的对象,因此您不得自动释放它。

-(ViewController*) getPluginViewController {
     self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
     return self.viewController;
}

就其本身而言,这还不错。在 Objective-C 中,按照惯例,以“get”开头的方法用于返回指针参数值的方法。但是,将其与您的称呼放在一起存在几个问题:

  • 原始分配的 ViewController 泄漏,因为此方法返回指向不同对象的指针
  • 原始分配的 ViewController 从未初始化
  • 返回的 ViewController 被自动释放两次。

【讨论】:

  • 非常感谢我现在看到了我的错误 - 我从来没有用 C 编程过,所以直接跳到 Objective C 对我来说很难:)
  • @user310291:是的,学习曲线可能有点陡峭,但是一旦你掌握了 Objective-C 的窍门,它就是一门不错的语言。
【解决方案2】:

注意双重分配。

您第一次使用[myPlugin alloc] 分配并调用getPluginViewController。 但是在getPluginViewController 中,您分配并初始化新的ViewController 并返回它。

【讨论】:

  • 我应该为我确定上下文:myPlugin 类是一回事,myPluginViewController 确实返回了一个插件的 suview,它没有主视图。在那种情况下,您认为还有什么问题吗?感谢您的帮助。
【解决方案3】:

删除ViewController和其他你认为有问题的类的引用。

如果需要,请转到查找器并通过取消选中“-copy”再次添加这些类。

从产品菜单中清理项目并运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 2018-11-17
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多