【问题标题】:IBOutlet with type id带有类型 id 的 IBOutlet
【发布时间】:2012-12-05 23:39:08
【问题描述】:

我是 Objective-C 的新手,正在努力读一本书。当我遇到错误时,我正在遵循一个非常基本的教程。代码与书中的代码相同。

我有 MyController.hMyController.m 的课程。错误发生在声明期间。

MyController.h:

#import <Foundation/Foundation.h>
@interface MyController : NSObject
@property (assign) IBOutlet id *textLabel;

- (IBAction)clickMeButtonClicked:(id)sender;
- (IBAction)deleteMeButtonClicked:(id)sender;

@end    

第三行给了我一个警告和一个错误:

错误:

Pointer to non-const type 'id' with no explicit ownership

警告:

Property with 'iboutlet' attribute must be an object type (invalid '__strong id *')

正如我所说,我刚刚开始学习,我肯定在这里遗漏了一些非常明显的东西。好像和'id'类型有关系,但是按照书上说,没有错。

感谢您的帮助!

【问题讨论】:

  • 多余的 * 实际上是问题所在。显然作者错过了这个错误。感谢所有指出这一点的人。
  • 我刚刚做了一些额外的研究,让您继续学习本教程的解决方案是@property (assign) IBOutlet NSTextField *textLabel;

标签: objective-c cocoa


【解决方案1】:

id 已经是一个指针:

typedef struct objc_object {
     Class isa;
} *id;

因此,声明中不需要*。试试:

@property (assign) IBOutlet id textLabel;

【讨论】:

  • 只是好奇,您在哪里找到id 类型的定义?我尝试使用 Xcode 的 go to definition 但它不想做任何事情
  • 我不在我的 Mac 上,所以我使用了 Google ;-) 这可能会有所帮助:stackoverflow.com/questions/1990695/…
【解决方案2】:

id 不需要声明为指针。正确的声明方式如下:

@property (assign) IBOutlet id textLabel;//Don't need the *

id类型可以在this question中找到更全面的解释

【讨论】:

  • 您能说得更具体一点吗?正确的做法是什么?
【解决方案3】:

Assign 应该改成 strong,去掉 textLabel 前的 *。

【讨论】:

    【解决方案4】:

    尝试将 (assign) 更改为 (nonatomic, retain),因为这是一个 IBOutlet 而不是原语,您必须保留并释放它。将 nonatomic 放在那里也是一个好习惯,它与线程有关,但我不能给你确切的信息。另外不要忘记把 [textLabel release] 在 dealloc 方法中,因为您需要释放您保留、创建或复制的每个对象。

    【讨论】:

      猜你喜欢
      • 2018-01-21
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 2021-12-16
      相关资源
      最近更新 更多