Xcode基础:使用整数属性声明自定义类,并在另一个类中使用它

时间:2012-07-21 22:23:53

标签: xcode class properties integer

尝试做一些非常简单的事情,但无法弄清楚语法。

我有一个名为Word.h的类,它有8个属性,字符串和整数。为了简单起见,我将坚持2:

#import <UIKit/UIKit.h>
@interface Word : NSObject
@property (nonatomic, strong) NSString *word; 
@property (nonatomic, strong) NSNumber *wordLevel;
@end

两个属性都在.m文件中合成

然后我想在另一个文件(UIViewController)中创建一些对象。在.h文件中我有:

#import "Word.h"

并在.m文件中,这个:

Word *newWord = [[Word alloc] init];
   [newWord setWord:@"theorise"];
   [newWord setWordLevel:6];

Word *newWord1 = [[Word alloc] init];
   [newWord setWord:@"implicit"];
   [newWord setWordLevel:7];

Word *newWord2 = [[Word alloc] init];
   [newWord setWord:@"incredible"];
   [newWord setWordLevel:9];

我现在收到一条错误消息“ARC禁止将'int'隐式转换为'NSNumber *'”

我做错了什么...是在类文件中错误定义的属性?我如何访问此属性。它适用于字符串。

我还想稍后访问这些属性 - 我该怎么做...例如:

cell.label1.text = [newWord2 wordLevel];

这是正确的语法???

希望有人可以帮助我,在这里撕下一堆头发! 中号

1 个答案:

答案 0 :(得分:2)

您将wordLevel声明为NSNumber,即对象。您在代码中对待它,就像它是普通的C int一样。你必须决定你想要的是什么,并始终如一地对待它。例如,对于普通的C int属性,您将改为声明:

@property (nonatomic, assign) int wordLevel;

另一方面,如果你真的希望wordLevel成为NSNumber,你需要像这样使用setter:

[newWord setWordLevel:[NSNumber numberWithInt:6]];