如何在Objective-C中向对象添加对象?

时间:2011-09-28 16:05:02

标签: objective-c object nsmutablearray add

我开始在Objective-C中编程。我正在使用一本书来学习第一批基础知识。给出的例子不起作用!我在代码中看不到问题 理解它并不是那么难,但它不会起作用。但是我在其他地方找到的一切,都像我一样添加了对象 我不知道语法是否改变了?我使用的是iOS 4.3 SDK和Xcode 3.2.6! 这部分失败了:

[questions addObject: @”What is 7 + 7?”]; //FAILS
[answers addObject: @”14”];

错误消息说:
/Applications/Quiz/Classes/QuizAppDelegate.m:32:0
Applications / Quiz / Classes / QuizAppDelegate.m:32:错误:'@'标记之前的预期表达式

如果有人可以帮助我,我会很高兴的! 谢谢!

我也附上了代码!

完整代码:.h:

#import <UIKit/UIKit.h>

@interface QuizAppDelegate : NSObject <UIApplicationDelegate> {

    int currentQuestionIndex;

    //The model objects
    NSMutableArray *questions;
    NSMutableArray *answers;

    //The view objects
    IBOutlet UILabel *questionField;
    IBOutlet UILabel *answerField;

    UIWindow *window;
}

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

-(IBAction)showQuestion:(id)sender;
-(IBAction)showAnswer:(id)sender;

@end

失败的部分代码:.m:

#import "QuizAppDelegate.h"

@implementation QuizAppDelegate

@synthesize window;

-(id)init{

    // Call the init method implemented by the superclass 
    [super init];

    // Create two arrays and make the pointers point to them 
    questions = [[NSMutableArray alloc] init]; 
    answers = [[NSMutableArray alloc] init];

    // Add questions and answers to the arrays 
    [questions addObject: @”What is 7 + 7?”]; //FAILS
    [answers addObject: @”14”];

    [questions addObject: @”Was ist die Hauptstadt von Madagaskar?”]; //FAILS
    [answers addObject: @”Antananarivo”];

    [questions addObject: @”Was ergibt 5-2*2+6?”]; //FAILS
    [answers addObject: @”7”];

    // Return the address of the new object 
    return self;

}

-(IBAction)showQuestion:(id)sender{

//Step to the next question
currentQuestionIndex++;

//Am I past the last question?
if(currentQuestionIndex==[questions count]){

    //Go back to the first question
    currentQuestionIndex=0;
}

// Get the string at that index in the questions array 
NSString *question = [questions objectAtIndex:currentQuestionIndex];

//Log the string to the console
NSLog(@"displaying question:%@",question);

//Display the string in the question field
[questionField setText:question];

//Clear the answer field
[answerField setText:@"???"];
}

-(IBAction)showAnswer:(id)sender{

//What is the answer to the current question
NSString *answer=[answers objectAtIndex:currentQuestionIndex];

//Display it in the answer field
[answerField setText:answer];
} 

2 个答案:

答案 0 :(得分:9)

我认为,你使用双引号的假字符“,就像你的那样。”你是否从某处复制并粘贴了代码?

答案 1 :(得分:-1)

甚至更短:

[myArray addObject:[NSString stringWithString:@"Wie hoch ist der Eiffelturm?"]];