Xcode 基础知识:声明具有整数属性的自定义类并在另一个类中使用它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11596307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:58:19  来源:igfitidea点击:

Xcode basics: Declare custom class with integer properties and use it in another class

xcodeclasspropertiesinteger

提问by InRainbows

Trying to do something really simple, but can't figure out the syntax.

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

I have a class called Word.h which has 8 properties, strings and integers. For the sake of keeping things simple, I'll stick to 2 here:

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

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

Both properties are synthesised in the .m file

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

I then want to create some objects in another file (UIViewController). In the .h file I have this:

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

#import "Word.h"

and in the .m file, this:

在 .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];

I now get an error message "Implicit conversion of 'int' to 'NSNumber *' is disallowed with ARC"

我现在收到一条错误消息“ARC 不允许将‘int’隐式转换为‘NSNumber *’”

What am I doing wrong...is the property defined incorrectly in the class file?? How do I access this property. It works fine with the string.

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

I will also want to access the properties later - how do I do that...for example:

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

cell.label1.text = [newWord2 wordLevel];

Is this the right syntax???

这是正确的语法吗???

Hoping someone can help me, tearing clumps of hair out here! M

希望有人可以帮助我,在这里撕掉一团头发!米

采纳答案by torrey.lyons

You declared wordLevelto be an NSNumber, an object. You are treating it in your code like it is a plain C int. You have to decide which your want it to be and treat it that way consistently. For example, for a plain C intproperty you would instead declare:

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

@property (nonatomic, assign) int wordLevel;

On the other hand if you really want wordLevelto be an NSNumberyou need to use the setter like this:

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

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