简体   繁体   English

在Objective-C iOS中增加/减少数字

[英]increase/decrease a number in Objective-C iOS

Im new in xcode and programming for iOS. 我是iOS的xcode和编程新手。 I have follow this tutorial: http://www.thetutorialblog.com/cocoa-objective-c/creating-a-basic-ipad-application/ 我已按照本教程进行操作: http : //www.thetutorialblog.com/cocoa-objective-c/creating-a-basic-ipad-application/

I got it working with one "- button", one label and one "+ button". 我使用了一个“-按钮”,一个标签和一个“ +按钮”。 But i want multiple of those, i have add the tutorial code and copy it like this: 但是我想要多个,我已经添加了教程代码并像这样复制它:

IBOutlet UILabel *currentNumber2;

-(IBAction)incrementNumber2:(id)sender2;
-(IBAction)decrementNumber2:(id)sender2;


-(IBAction)incrementNumber2:(id)sender2 {
    number++;
    [currentNumber2 setText:[NSString stringWithFormat:@"%d", number]];
}


-(IBAction)decrementNumber2:(id)sender2 {
    number--;
    [currentNumber2 setText:[NSString stringWithFormat:@"%d", number]];
}

But when I press the first + button, it count up +1 in first label, then when I press the second + button, it continue counting from first button in label2 so it put in 2. Understand? 但是,当我按下第一个+按钮时,它会在第一个标签中向上计数+1,然后当我按下第二个+按钮时,它会继续从label2中的第一个按钮开始计数,然后放入2中。

This is a quintessential behavior of object-oriented programming: that single instance of number is shared across every method call on that object. 这是面向对象编程的典型行为: number单个实例在该对象的每个方法调用之间共享。 If you want to support multiple number instances, you have two choices: add more instance variables to your class and start adding more and more code as you make more instances, or simply spawn a new instance of your class. 如果要支持多个number实例,则有两种选择:向类中添加更多实例变量,并在创建更多实例时开始添加越来越多的代码,或者只是生成类的新实例。

Note that you will very quickly make a valuable realization: Sometimes the modeled domain has different object requirements than our application domain (ie you should be saying "But I shouldn't have to make more instances of my UIViewController !!", and you're right). 请注意,您将很快实现一个有价值的实现:有时, 建模域与我们的应用程序具有不同的对象要求 (即,您应该说“但是我不必为UIViewController制作更多实例!”,并且正确)。 This is the first step toward an architecture which iOS deeply supports: Model-View-Controller. 这是迈向iOS 深深支持的体系结构的第一步:模型-视图-控制器。 Your Model, in this case number , should be decoupled from the controller, which should be capable of handling any quantity of them (not just as many as you happened to create ivars for). 您的模型(在这种情况下为number )应与控制器分离,控制器应能够处理任意数量的控制器(不仅仅是您创建ivars的数量)。

It's a good path to be on :-) 这是一条不错的路:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM