2014-01-29 21 views
1

我目前在教自己Objective-C作爲第一語言。我明白所涉及的困難,但我卻是一個堅忍不拔的人。我已經開始在Apple Objective-C文檔上進行練習。我的目標是讓我的程序註銷我的名字和姓氏,而不是通用的Hello World問候語。Objective-C練習未聲明的標識符錯誤

我不斷收到使用未聲明的標識符錯誤。我試圖找出是什麼導致了錯誤。

這裏是introClass.h

#import <UIKit/UIKit.h> 

    @interface XYZperson : NSObject 

    @property NSString *firstName; 
    @property NSString *lastName; 
    @property NSDate *dateOfBirth; 
    - (void)sayHello; 
    - (void)saySomething:(NSString *)greeting; 
    + (instancetype)person; 
    -(int)xYZPointer; 
    -(NSString *)fullName; 
    @end 

這裏是IntroClass.m

#import "IntroClass.h" 

@implementation XYZperson 
-(NSString *)fullName 
{ 
    return[NSString stringWithFormat:@" %@ %@", self.firstName, self.lastName]; 
} 

-(void)sayHello 
{ 
    [self saySomething:@"Hello %@", fullName]; //use of undeclared identifier "fullName" 
}; 

-(void)saySomething:(NSString *)greeting 
{ 
    NSLog(@"%@", greeting); 
} 

+(instancetype)person{ 
    return [[self alloc] init]; 
}; 

- (int)xYZPointer { 
    int someInteger; 
    if (someInteger != nil){ 
     NSLog(@"its alive"); 
    } 
    return someInteger; 
}; 


@end 

回答

2

的問題是,fullName是一個方法的名稱。應在0​​上用方括號調用。

由於saySomething:需要一個單一的參數,則需要:(1)除去該呼叫的@"Hello %@"部分,像這樣:

-(void)sayHello { 
    [self saySomething:[self fullName]]; 
}; 

,或者從@"Hello %@"[self fullName],這樣使一個單一的字符串:

-(void)sayHello { 
    [self saySomething:[NSString stringWithFormat:@"Hello %@", [self fullName]]]; 
}; 
+0

這將返回一個錯誤:有太多的參數的方法調用,預計1,2,有@ – TheM00s3

+0

user3084800看看校正。 – dasblinkenlight

+0

非常感謝,它工作!你能否解釋爲什麼SayHello方法只允許1個參數? – TheM00s3

0

使用

[self saySomething:@"Hello %@", self.fullName]]; 

[self saySomething:@"Hello %@", [self fullName]]; 
1

您傳回的姓和名的字符串,但我沒有看到任何地方,你已經爲他們設定的值。正如其他人指出嘗試

-(void)sayHello 
    { 
     _firstName = [NSString stringWithFormat:@"John"]; 
     _lastName = [NSString stringWithFormat:@"Doe"]; 

     //if you want to see what's happening through out your code, NSLog it like 
     NSLog(@"_firstName: %@ ...", _firstName); 
     NSLog(@"_lastName: %@ ...", _lastName); 

     NSString *strReturned = [self fullName]; 
     NSString *concatStr = [NSString stringWithFormat:@"Hello %@", strReturned]; 

     NSLog(@"strReturned: %@ ...", strReturned); 
     NSLog(@"concatStr: %@ ...", concatStr); 

     [self saySomething:concatStr]; 
    }; 

    -(NSString *)fullName 
    { 
     return[NSString stringWithFormat:@" %@ %@", self.firstName, self.lastName]; 
    } 
+0

我試過第二種方法,它會自動將firstName更改爲_firstName,lastName更改爲_lastName。我在[self saysomething:@「hello%@」,[self fullname]]上得到一個錯誤;這表明:太多的方法調用參數,預期1,有2. – TheM00s3

+0

看到我更新的答案 –