Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        6年前关闭。
                                                                                            
                
        
我不太了解目标C以及属性和参数如何工作。
我似乎遇到了面向对象的设计错误:我试图将有关对象状态的信息传递给其中一种方法。有人可以向我解释此代码如何与以其firstName和lastName作为参数的Person类一起使用:

Person.m
#import "Person.h"

@implementation Person
- (NSString *)fullNameWithFirstName:(NSString *)firstName lastName:(NSString *)lastName;
{
  return [NSString stringWithFormat:@"%@ %@", firstName, lastName];
}
@end


我该如何解决这个错误?
我试图开始解决此设计错误,并在Name中添加了self,但它总是给我带来意外错误。谢谢并恭祝安康。

最佳答案

目前,您在做什么并没有多大意义。您发布的方法没有什么不同,只是在调用此方法的地方调用[NSString stringWithFormat:]。您无需在课程中进行任何修改。您不会从类中检索数据。



假设Person类用于保存一个人的名字,则头文件可能具有以下一些属性:

@property (nonatomic,strong) NSString *firstName;
@property (nonatomic,strong) NSString *lastName;
@property (readonly,nonatomic,strong) NSString *fullName;


.m文件将包含几种不同类型的方法。


init方法
factory方法
您要覆盖的任何属性访问器的accessor方法
以及您可能需要的其他其他方法,具体取决于您对类进行的操作。




给定我们假设的属性已在标头中声明,则可以设置或检索名字,设置或检索姓氏。您也可以尝试检索姓氏,但是.m中没有任何逻辑来设置它(并且.m之外是只读的),它只会返回nil。如果不将任何内容放入.m文件,则以下内容均有效:

Person *person = [[Person alloc] init];
person.firstName = @"John";
person.lastName = @"Doe";
NSLog(@"%@ %@", person.firstName, person.lastName); //prints "John Doe"




由于fullName实际上只是名字和姓氏的串联,因此可以覆盖它的getter(在我们标记为readonly时没有setter),以防止我们的类保留实例变量。这样看起来像这样:

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


现在,fullName属性可以动态生成一个fullName字符串,并返回该字符串,而不是为此在内存中保留单独的变量。



称为fullNameWithFirstName:lastName:的方法似乎适合作为factory方法,但是按照命名约定,实际上应将其称为personWithFirstName:lastName:

它实际上应该看起来像这样:

+(instancetype)personWithFirstName:(NSString*)firstName
    lastName:(NSString*)lastName {
    return [[Person alloc] initWithFirstName:firstName lastName:lastName];
}


因此,它仅调用一个指定的初始化器,可能看起来像这样:

-(id)initWithFirstName:(NSString*)firstName lastName:(NSString*)lastName {
    self = [super init];
    if(self) {
        self.firstName = firstName;
        self.lastName = lastName;
    }
    return self;
}


使用此代码,您可以执行以下操作:

Person *person = [[Person alloc] initWithFirstName:@"Steve" lastName:@"Jobs"];
Person *person2 = [Person fullNameWithFirstName:@"Bill" lastName:@"Gates"];


两种方式都会使personperson2成为Person类型的对象,这将为如下调用返回正确的值:

person.firstName
person.lastName
person.fullName

07-25 22:36
查看更多