我是iOS和Objective-C编程的新手,尝试(HARD)学习它,所以我参加了基础课程。我正在尝试IBAcion
在ViewController.m文件中实现2 ,但是我对这个问题的思考方式以及理解范围的困难似乎存在问题,例如我可以调用和不能调用的东西。
其中一个IBAction
将掷出骰子,获得正确的图像,另一个将保存结果并显示最新的10个投掷。
请不要因似乎很多代码而灰心。
这些是我在@interface
(.h文件)中声明的以下属性
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIImageView *dieOne;
@property (weak, nonatomic) IBOutlet UIImageView *dieTwo;
@property (weak, nonatomic) IBOutlet UILabel *latestTenThrows;
@property (nonatomic) NSUInteger dieValue1;
@property (nonatomic) NSUInteger dieValue2;
@property (nonatomic) NSUInteger totalValue;
@property (nonatomic) NSMutableArray *rolledDiceArray;
@property (nonatomic) NSMutableString *rolledDiceString;
@end
这是我的实现
- (IBAction)throwDice {
NSMutableArray *dieArray = [[NSMutableArray alloc] initWithObjects:
@"one", @"two", @"three", @"four", @"five", @"six", nil];
NSUInteger dieIndex1 = arc4random_uniform(6);
NSUInteger dieIndex2 = arc4random_uniform(6);
UIImage *image1 = [UIImage imageNamed:[dieArray objectAtIndex:dieIndex1]];
UIImage *image2 = [UIImage imageNamed:[dieArray objectAtIndex:dieIndex2]];
self.dieOne.image = image1;
self.dieTwo.image = image2;
到目前为止,一切都很好,显示的是正确的图像,但是这对我来说很棘手。我正在尝试“保存”掷骰子值,并在象这样的标签中显示它们:视图中5 + 2 = 7,它应该显示最近的10个掷骰子。
self.dieValue1 = (dieIndex1+1);
self.dieValue2 = (dieIndex2+1);
self.totalValue = self.dieValue1 + self.dieValue2;
NSMutableString *rolledDiceString = [[NSMutableString alloc] init];
[rolledDiceString appendString:[NSString stringWithFormat:
@"%d + %d = %d",
self.dieValue1,self.dieValue2,self.totalValue]];
在- (IBAction)saveThrow{}
下面的其他函数中,我如何获得对该数组的许可?
NSMutableArray *rolledDiceArray = [[NSMutableArray alloc]init];
[rolledDiceArray addObject:rolledDiceString];
如果我添加此NSLog调用,则无论我在界面中点击“ Roll dice”多少次,我都只会得到1,这意味着当我在界面中点击“ Roll dice”时,它不会将创建的值放入字符串,正确地放置在数组中。如何将字符串正确添加到数组中,以便以后可以从另一个IBAction中检索该信息?在下面的函数中,我是否对此数组具有权限?
NSLog(@"%d",rolledDiceArray.count);
} // End for -(IBAction)throwDice{
在我的第二个也是最后一个IBAction中,我试图将字符串添加到标签中,但是由于数组无法获取字符串而在这里出现了问题。
- (IBAction)saveThrow {
NSMutableArray *savedThrowsArray = [[NSMutableArray alloc] init];
[savedThrowsArray addObject:self.rolledDiceArray];
self.latestTenThrows.text = [// Latest 10 items (strings) in savedThrowsArray];
}
不要连fl;想想你在做什么。您的词(在您的代码中)具有含义。电脑只能执行您要执行的操作...!因此,让我们看一下:
NSMutableArray *rolledDiceArray = [[NSMutableArray alloc]init];
[rolledDiceArray addObject:rolledDiceString];
每次运行该代码时,您都在创建一个全新的空可变数组(这就是= [[NSMutableArray alloc] init]
第一行中的含义)。因此,无论您运行多少次,结果数组都将只包含一个对象(该对象在的第二行中添加addObject
)。
NSMutableArray *savedThrowsArray = [[NSMutableArray alloc] init];
[savedThrowsArray addObject:self.rolledDiceArray];
同样的交易。
同时,您还没有使用这些完全不同的实例变量:
@property (nonatomic) NSMutableArray *rolledDiceArray;
@property (nonatomic) NSMutableString *rolledDiceString;
但是,您的任何代码都从未与他们谈过/谈论过它们。他们只是坐在那里浪费。您需要初始化它们并将数据放入其中-而不是一直创建并丢弃的这些局部自动变量中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句