Cocoa Touch - 按下按钮时iPhone App崩溃了吗?

时间:2010-07-11 14:56:31

标签: objective-c cocoa cocoa-touch debugging

这是我的第一个应用。它不会崩溃模拟器只会让你回到主屏幕。这不是我的第一个可可程序(我不是可可的专业人士)只是我的第一部iPhone。

按下运行-(IBAction)letsPlay:(id)sender;方法的letsPlayButton时崩溃。

救救我!我迷失了什么是错的!

.H

#import <UIKit/UIKit.h>

@interface BrainiacViewController : UIViewController {
    IBOutlet    UILabel     *theQuestion;
    IBOutlet    UILabel     *theScore;
    IBOutlet    UILabel     *theLives;
    IBOutlet    UIButton    *answerOne;
    IBOutlet    UIButton    *answerTwo;
    IBOutlet    UIButton    *answerThree;
    IBOutlet    UIButton    *answerFour;
    IBOutlet    UIButton    *letsPlayButton;
    NSString  *questionNumber;
    NSInteger myScore;
    NSInteger myLives;
    NSInteger usersAnswer;
    NSArray   *theQuiz;

    //quiz dictionarys
    NSMutableDictionary *question, *rightAnswer, *wrongOne, *wrongTwo, *wrongThree;
}

-(IBAction)buttonOne:(id)sender;
-(IBAction)buttonTwo:(id)sender;
-(IBAction)buttonThree:(id)sender;
-(IBAction)buttonFour:(id)sender;
-(IBAction)letsPlay:(id)sender;

-(void)checkAnswer;

-(void)askQuestion;

-(void)updateScore;

-(void)loadQuiz;
@end

.M

#import "BrainiacViewController.h"

@implementation BrainiacViewController

-(void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (void)dealloc {
    [super dealloc];
}

-(IBAction)buttonOne:(id)sender{
    usersAnswer = 1;
}
-(IBAction)buttonTwo:(id)sender{
    usersAnswer = 2;
}
-(IBAction)buttonThree:(id)sender{
    usersAnswer = 3;
}
-(IBAction)buttonFour:(id)sender{
    usersAnswer = 4;
}
-(IBAction)letsPlay:(id)sender{
    //un hide answer buttons
    [answerOne setHidden:NO];
    [answerTwo setHidden:NO];
    [answerThree setHidden:NO];
    [answerFour setHidden:NO];

    //hide the lets play button
    [letsPlayButton setHidden:YES]; 

    //assign values to variables
    myScore = 0;
    myLives = 3;
    questionNumber = 0; 
    //ask question and start game
    [self askQuestion];
}


-(void)checkAnswer{
    [question objectForKey:questionNumber];
    [rightAnswer objectForKey:questionNumber];
    [wrongOne objectForKey:questionNumber];
    [wrongTwo objectForKey:questionNumber];
    [wrongThree objectForKey:questionNumber];

}

-(void)askQuestion{
    //create array to mix up the possible answers
    NSMutableArray *possibleAnswers = [[NSMutableArray alloc] init];
    [possibleAnswers addObject:[rightAnswer objectForKey:questionNumber] ];
    [possibleAnswers addObject:[wrongOne objectForKey:questionNumber] ];
    [possibleAnswers addObject:[wrongTwo objectForKey:questionNumber] ];
    [possibleAnswers addObject:[wrongThree objectForKey:questionNumber] ];


    //set labels/buttons for question
    theQuestion.text = [question objectForKey:questionNumber];


    //user picks a answer button and sets a value to usersAnswer
    questionNumber = questionNumber + 1;
    [self checkAnswer];

}

-(void)updateScore{
}

-(void)loadQuiz{ //assigns dictionary values
    //*KEY* defines question number
    [question    setObject:@"Which is NOT a starwars movie?" forKey:@"1"];
    [rightAnswer setObject:@"Attack of the Jedi" forKey:@"1"];
    [wrongOne    setObject:@"A New Hope" forKey:@"1"];
    [wrongTwo    setObject:@"The Phantom Menace" forKey:@"1"];
    [wrongThree  setObject:@"Attack of the Clones" forKey:@"1"];

    [question    setObject:@"In what state is the majority of Yellow Stone National Park in?" forKey:@"2"];
    [rightAnswer setObject:@"Wyoming" forKey:@"2"];
    [wrongOne    setObject:@"California" forKey:@"2"];
    [wrongTwo    setObject:@"Ohio" forKey:@"2"];
    [wrongThree  setObject:@"Nebraska" forKey:@"2"];

    [question    setObject:@"In the US, what household pet is the most common?" forKey:@"2"];
    [rightAnswer setObject:@"Dogs" forKey:@"2"];
    [wrongOne    setObject:@"Cats" forKey:@"2"];
    [wrongTwo    setObject:@"Hamsters" forKey:@"2"];
    [wrongThree  setObject:@"Komodo Dragons" forKey:@"2"];

    [question    setObject:@"A plane is traveling 2675 miles every 5 hours. How fast is the plane going in Miles per Hour?" forKey:@"3"];
    [rightAnswer setObject:@"535 Mph" forKey:@"3"];
    [wrongOne    setObject:@"325 Mph" forKey:@"3"];
    [wrongTwo    setObject:@"535 Mph" forKey:@"3"];
    [wrongThree  setObject:@"420 Mph" forKey:@"3"];
}
@end

appdelagate.h

#import <UIKit/UIKit.h>

@class BrainiacViewController;

@interface BrainiacAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    BrainiacViewController *viewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet BrainiacViewController *viewController;

@end

appdelegate.m

#import "BrainiacAppDelegate.h"
#import "BrainiacViewController.h"

@implementation BrainiacAppDelegate

@synthesize window;
@synthesize viewController;


#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    // Override point for customization after application launch.

    // Add the view controller's view to the window and display.
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];

    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}


- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}

- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}


@end

我再次尝试并检查控制台,错误是这个......我不知道这意味着什么。

[Session started at 2010-07-11 12:24:40 -0400.]
2010-07-11 12:24:45.729 Brainiac[46764:207] -[NSCFString letsPlay:]: unrecognized selector sent to instance 0x5944f00
2010-07-11 12:24:45.733 Brainiac[46764:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString letsPlay:]: unrecognized selector sent to instance 0x5944f00'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x02395919 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x024e35de objc_exception_throw + 47
    2   CoreFoundation                      0x0239742b -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
    3   CoreFoundation                      0x02307116 ___forwarding___ + 966
    4   CoreFoundation                      0x02306cd2 _CF_forwarding_prep_0 + 50
    5   UIKit                               0x002b9e14 -[UIApplication sendAction:to:from:forEvent:] + 119
    6   UIKit                               0x003436c8 -[UIControl sendAction:to:forEvent:] + 67
    7   UIKit                               0x00345b4a -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
    8   UIKit                               0x003446f7 -[UIControl touchesEnded:withEvent:] + 458
    9   UIKit                               0x002dd2ff -[UIWindow _sendTouchesForEvent:] + 567
    10  UIKit                               0x002bf1ec -[UIApplication sendEvent:] + 447
    11  UIKit                               0x002c3ac4 _UIApplicationHandleEvent + 7495
    12  GraphicsServices                    0x02bfbafa PurpleEventCallback + 1578
    13  CoreFoundation                      0x02376dc4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
    14  CoreFoundation                      0x022d7737 __CFRunLoopDoSource1 + 215
    15  CoreFoundation                      0x022d49c3 __CFRunLoopRun + 979
    16  CoreFoundation                      0x022d4280 CFRunLoopRunSpecific + 208
    17  CoreFoundation                      0x022d41a1 CFRunLoopRunInMode + 97
    18  GraphicsServices                    0x02bfa2c8 GSEventRunModal + 217
    19  GraphicsServices                    0x02bfa38d GSEventRun + 115
    20  UIKit                               0x002c7b58 UIApplicationMain + 1160
    21  Brainiac                            0x00002790 main + 102
    22  Brainiac                            0x00002721 start + 53
)
terminate called after throwing an instance of 'NSException'

2 个答案:

答案 0 :(得分:3)

  

我再次尝试并检查控制台,错误是这个......我不知道这意味着什么。

2010-07-11 12:24:45.729 Brainiac[46764:207] -[NSCFString letsPlay:]: unrecognized selector sent to instance 0x5944f00

您向不响应该消息的对象发送了消息(letsPlay:)(NSString,此处显示为NSCFString)。

这种情况通常会发生,因为您没有正确地抓住您要发送letsPlay:的对象,因此它已被取消分配。 NSString后来被分配在同一个地址,因此所有持有旧对象指针(并认为它仍然是)的东西现在都持有指向NSString的指针。相同的指针,不同的对象。然后,当其中一个可能的所有者试图将消息发送到它认为仍然有...的对象时,就会繁荣。

修复方法是检查您的所有权,并确保您保留(或使用alloc创建而不是自动释放)您的意思。

在相关说明中:

NSMutableArray *possibleAnswers = [[NSMutableArray alloc] init];
[possibleAnswers addObject:[rightAnswer objectForKey:questionNumber] ];
[possibleAnswers addObject:[wrongOne objectForKey:questionNumber] ];
[possibleAnswers addObject:[wrongTwo objectForKey:questionNumber] ];
[possibleAnswers addObject:[wrongThree objectForKey:questionNumber] ];

如果您的意思是本地变量,则必须在方法结束时释放它,否则您将泄漏此数组。

如果你想拥有这个对象,你应该将它移动到一个实例变量,并删除局部变量,并继续像现在一样创建对象。

必读:Memory Management Programming Guide for Cocoa

答案 1 :(得分:0)

您需要在questionNumber对象中“装箱”整数NSNumber,如下所示:

theQuestion.text = [question objectForKey:[NSNumber numberWithInt:questionNumber]];

或者,您可以使用更合适的NSArray索引器:

theQuestion.text = [question objectAtIndex:questionNumber];