这个阵列怎么了?每当我运行动作时它都会锁定

时间:2009-07-30 18:26:35

标签: iphone objective-c arrays

为什么这段代码不起作用?该应用程序加载正常,但每当我按下按钮时,应用程序锁定(不会崩溃)并将我返回到Xcode,并且有一个指向其中一条线的红色箭头(在下面的行中显示)。

我还得到三个警告(不是错误),一个说'NSMutableArray'可能不响应'-objectAt:'而第二个说未使用的变量'soundToPlay'第三个说隐含声明函数'AudioServicesPlaySystemSound'我应该关注那些?

    //In MainViewController.h

    @interface MainViewController : UIViewController {
        IBOutlet UIButton *Button;      
    }

    @property (nonatomic, retain) UIButton *Button;

    - (IBAction)playSound;

    NSInteger currentSound;
    NSMutableArray *soundArray;

    @end




    //In MainViewController.m

        - (void)viewDidLoad {
        currentSound = 0;
        NSMutableArray *sounds = [[NSMutableArray alloc] init];
        [sounds addObject: @"0.wav"];
        [sounds addObject: @"1.wav"];
        [sounds addObject: @"2.wav"];
        [sounds addObject: @"3.wav"];
        [sounds addObject: @"4.wav"];
        [sounds addObject: @"5.wav"];
        [sounds addObject: @"6.wav"];
        [sounds addObject: @"7.wav"];
        [sounds addObject: @"8.wav"];
        [sounds addObject: @"9.wav"];
        [sounds addObject: @"10.wav"];
        [sounds addObject: @"11.wav"];
        [sounds addObject: @"12.wav"];
        [sounds addObject: @"13.wav"];
        [super viewDidLoad];
    }

    - (IBAction)playSound {
        NSString *soundToPlay = [soundArray objectAt: currentSound];
//First two errors here.
        currentSound = (currentSound + 1) % [soundArray count]; //Red arrow points to this line.
        AudioServicesPlaySystemSound (currentSound);
//Third error here.
    }

2 个答案:

答案 0 :(得分:2)

第一个: methodname不存在。你的意思是写objectAtIndex而不是objectAt。 当它说对象现在可能响应'-something'时,因为这些方法没有在头文件中声明。这导致编译器无法确定该方法是否存在于实现文件中。当您使用内置类(NSArray,NSView等)时,这些类型的警告通常意味着您拼错了方法名称。唯一要做的就是在文档中查找并进行双重检查。当尝试将消息发送到未响应选择器的对象时,这些类型错误将导致应用程序崩溃。

第二个: 这只是一个警告,告诉你没有使用变量。删除该行。正如您所看到的,playSound方法中没有使用soundToPlay,它只是被声明。 如果你使用它fx。使用NSLog函数调用或在方法中,此警告应该消失。

第三个: 您可能使用了错误的功能。不能说你发布的代码..

其他 丹尼尔是对的。您的viewDidLoad方法正在创建一个本地数组,并且永远不会将其存储在soundArray实例变量中。为此,请添加

soundArray = sounds

在方法的底部。或者直接写入soundsArray而不是声音。

答案 1 :(得分:1)

从看到的代码中,似乎你没有初始化soundArray,你在viewDidLoad中填充一个名为sounds的局部变量,并且从不设置soundArray ......