【问题标题】:adding a func in an objective-c category在 Objective-C 类别中添加 func
【发布时间】:2009-02-28 01:38:57
【问题描述】:

我是一个客观的 C 新手。为什么调用我在类别中创建的函数时会收到警告?

#import <stdio.h>
#import <objc/Object.h>

@interface MyObj: NSObject
{
@public
    int  num;
}

-(void) print;
@end

@implementation MyObj;
-(void) print
{
    printf("%d\n", self->num);
}
@end

@implementation MyObj(more)
-(void) quack
{
    printf("Quack\n");
}
@end


int main (int argc, char *argv[])
{
    MyObj  *obj = [[MyObj alloc] init];
    obj->num = 9;
    [obj print];
    [obj quack]; //warning my not respond to quack 
    [obj release]; 
}

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    你需要为 MyObj(more) 声明接口,例如。

    @interface MyObj(more)
    -(void)quack;
    @end
    

    【讨论】:

      【解决方案2】:

      只是想指出几件事,因为您提到您是 Obj-C 的新手。

      在方法内部,你不需要引用self-&gt;来获取实例变量,所以你的print方法可以是:

      -(void) print
      {
          printf("%d\n", num);
      }
      

      另外请注意,您通常从不直接访问对象方法之外的实例变量(即,您不会使用 obj-&gt;num -- 事实上,您不会经常在 Obj-C 代码中看到 -&gt; 运算符) .相反,您应该为属性指定访问器(假设这是 Objective-C 2.0):

      // In the interface:
      @property (assign) int num;
      
      // In the implementation:
      @synthesize num;
      
      // In main:
      obj.num = 9;
      

      【讨论】:

      • 很高兴知道。看来我使用的是 2.0。谢谢 :)。这看起来好多了
      猜你喜欢
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多