将视图的NSinteger属性设置为NSInteger?

3

我正在尝试在即将加载的视图上设置一个变量。以下是设置它的代码:

 NSInteger amountOfQuestions = [self.questions.text intValue];
    Timer_ViewController *tvc = [[Timer_ViewController alloc] initWithNibName:@"Timer_ViewController" bundle:nil];

    tvc.amountOfQuestions = &amountOfQuestions;

这里是 Timer_ViewController 的 @interface:

@interface Timer_ViewController : UIViewController
{
    NSInteger amountOfQuestions;
}

    @property (nonatomic) NSInteger *amountOfQuestions;



@end

我相对较新于Objective-C,因此指出明显的设计缺陷将不胜感激。

1个回答

9

您不应该将NSInteger设置为指针 - 它不是对象类型,只是一个普通基本类型的typedef。如果您使用的是相对较新的Xcode版本,则可以使用以下代码:

@interface Timer_ViewController : UIViewController
@property (nonatomic, assign) NSInteger amountOfQuestions;
@end

使用以下方式进行设置:

tvc.amountOfQuestions = [self.questions.text intValue];

您甚至不需要声明实例变量或@synthesize属性 - Xcode会为您处理它。


这给了我错误/警告:“不兼容的整数到变量转换..” - Jonah Katz
始终省略“assign”。它没有任何作用。 - SmileBot
尊敬的,那是一种风格偏好。对我来说,在属性声明中明确包含“assign”提醒我 - 即使不必考虑语言默认值或查看属性类型 - 该属性没有对象语义。在维护代码时,我肯定会称之为“有用”。 - Tim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接