如何在 Objective C 中的参数化构造函数中初始化 NSDate?

How to initialise NSDate in a parameterised constructor in Objective C?

这是在 Objective C 中编写的代码,我在其中将值初始化为参数化构造函数。虽然所有字段都正确输入,但我在 NSDate 字段中输入时遇到问题。下面给出了构造函数声明、实现和最后的方法调用。

//初始化声明

-(instancetype)initWithParam1:(NSNumber*)customerId_ withParam2:   (NSString*)firstName_ withParam3:(NSString*)lastName_ withParam4:(NSDate*)dateOfBirth_ withParam5:(NSString*)address_ withParam6:(NSNumber*)mobileNumber_;

//初始化定义

-(instancetype)initWithParam1:(NSNumber *)customerId_ withParam2:(NSString *)firstName_ withParam3:(NSString *)lastName_ withParam4:(NSDate *)dateOfBirth_ withParam5:(NSString *)address_ withParam6:(NSNumber *)mobileNumber_

{
    self = [super init];
    if(self)
    {
        self.customerId = customerId_;
        self.firstName = firstName_;
        self.lastName = lastName_;
        self.dateOfBirth = dateOfBirth_;
        self.address = address_;
        self.mobileNumber = mobileNumber_;
    }
    return self;

//初始化调用

Customer *c1 = [[Customer alloc]initWithParam1:@1001 withParam2:@"Aman" withParam3:@"Zaidi" withParam4:@"22-05-1993" withParam5:@"Bangalore" withParam6:@9567812345];

有关如何在该字段中输入日期的任何建议。很抱歉我太天真了,但我对 Objective C 完全陌生,而且我已经习惯了这些语法。

日期是一个字符串。

您需要将参数更改为NSString

... withParam4:(NSString *)dateOfBirth_ ...

并在 init 方法中使用 NSDateFormatter

将字符串转换为 NSDate
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"dd-MM-yyyy";
self.dateOfBirth = [formatter dateFromString:dateOfBirth_];