-1

我正在编写 Apple 开发人员 pdf 第 76 页的练习 3,位于类类别和扩展部分“使用 Objective C 编程”中,可在此处找到:( https://developer.apple.com/library/mac/documentation/cocoa /conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html )

我的 XYZPerson 标题如下所示:

#import <Foundation/Foundation.h>

@interface XYZPerson : NSObject

@property (readonly) NSNumber *height;
@property (readonly) NSNumber *weight;

-(NSNumber *)measureHeight;
-(NSNumber *)measureWeight;

@end

我的实现文件如下所示:

#import "XYZPerson.h"

@property (readwrite) NSNumber *height;
@property (readwrite) NSNumber *weight;

@end
/////////////////////

@implementation XYZPerson

-(NSNumber *)measureHeight{
    if(!_height){
        _height = [[NSNumber alloc] init];
    }
    return _height;
}

-(NSNumber *)measureWeight{
    if(!_weight){
        _weight = [[NSNumber alloc] init];
    }
    return _weight;
}

@end

然后在我的主文件中我有:

#import <Foundation/Foundation.h>
#import "XYZPerson.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        XYZPerson *aPerson = [[XYZPerson alloc] init];

        [aPerson setHeight: [NSNumber numberWithInt:72] ];
        [aPerson setWeight: [NSNumber numberWithInt:190] ];
        NSLog(@"%@ %@",[aPerson measureHeight],[aPerson measureWeight]);
    }
    return 0;
}

可能有不止一个错误与我提出的问题无关,我现在是 Objective C 的新手。我得到的确切编译器错误是在上面写着的那一行,

[aPerson setHeight: [NSNumber numberWithInt:72] ];

编译器错误显示,“ARC 语义问题。‘XYZperson’没有可见的@interface 声明选择器‘setWeight:’。

4

4 回答 4

0

您在头文件中将属性声明为只读,因此对于类之外的所有内容,正确的是只读的,因此setHeight:方法不存在。

于 2014-09-04T17:57:10.933 回答
0

您已将他的属性身高和体重设为只读。然后在主函数中使用 setWeight 和 setHeight。

你不能这样做,因为那会写权重,但你明确地将它们设置为只读。

于 2014-09-04T17:58:06.103 回答
0

哦,多哈。

您将无法从类实现的外部调用该方法。覆盖 .m 文件中的类扩展中的属性不会将其暴露给世界。至少不是编译器。

这就是重点。这是因为当您想要对该对象外部的世界只读的属性时,您仍然希望能够方便地做事情的对象内部。

于 2014-09-06T04:28:57.827 回答
0

将您的属性放在带有类扩展名的 .m 中:

@interface XYZPerson ()

@property (readwrite) NSNumber *height;
@property (readwrite) NSNumber *weight;

@end

请参阅有关类扩展的 Apple 文档: https ://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html

于 2014-09-06T04:38:22.513 回答