【问题标题】:Objective C class extension. Not able to assign value to readwrite property目标 C 类扩展。无法为读写属性赋值
【发布时间】:2014-05-13 18:02:50
【问题描述】:

我是 Objective C 的新手,并且正在使用 IOS 开发人员库学习类扩展。在自定义现有类中,我被要求创建一个只读属性,然后还创建一个与 readwrite 具有相同属性的类扩展。

//XYZPerson.h
@property (readonly) NSInteger height;
@property (readonly) NSInteger weight;
   -(NSInteger) measureHeight;
   -(NSInteger) measureWeight;

//XYZPerson.m
@interface XYZPerson() //class extension
  @property (readwrite) NSInteger height;
  @property (readwrite) NSInteger weight;
@end

@implementation XYZPerson

-(NSInteger) measureHeight
{
    self.height = 100;
    return self;
}

-(NSInteger) measureWeight
{
    self.weight = 80;
    return self;
}

我的目标是分配身高和体重值。当我构建时,我收到一个编译器警告:指向整数转换的指针不兼容,从结果类型为'NSInteger'(又名'long')的函数返回'XYZPerson *const __strong'”当我运行程序时,高度和重量值为0;

将值分配给 NSInteger 属性的语法是否有误?

【问题讨论】:

    标签: objective-c


    【解决方案1】:
    -(NSInteger) measureHeight
    {
        self.height = 100;
        return self;
    }
    

    self 是一个对象,而不是 NSInteger。也许您想改为return self.height

    您收到的错误消息是不言自明的:

    从结果类型为“NSInteger”的函数返回“XYZPerson *”

    显然意味着你没有返回正确的东西。

    【讨论】:

    • 谢谢!这是一个很好的提示!这消除了警告。但是,现在当我尝试对 self.height 和 self.weight 进行 NSLog 记录时,结果仍然为 0(非空)。我的 NSLos 在同一个 XYZPerson.m 文件中。有什么建议吗?
    猜你喜欢
    • 2010-09-18
    • 2017-02-17
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多