gpt4 book ai didi

objective-c - 删除用于提交到服务器的 NSDictionary Params 中的重复代码

转载 作者:行者123 更新时间:2023-11-29 04:51:17 27 4
gpt4 key购买 nike

下面的代码显示了我准备将参数提交到服务器的方式。我有一个 if-else 子句来检查并确定要提交哪些参数,即如果问题 id 存在,则仅提交问题 id,否则提交问题文本和主题 id。

但是,我觉得这有点重复,而且不是最好的编码形式(在我的 POV 中)。如何重构代码以使其更加高效(删除重复)

if(self.question._id || [self.question._id isEqual:[NSNull null]])
{
//Set up params for submission
NSDictionary *params= [[NSDictionary alloc] initWithObjectsAndKeys:
self.answer.text, @"text",
//if question id exists, submit question id only
self.question._id, @"question_id",
shareFb, @"fbShare",
shareTwitter, @"twitterShare",
self.question.source,@"questionSource",
self.answer.videoId,@"youtube_id",
nil
];
}
else
{
//Set up params for submission
NSDictionary *params= [[NSDictionary alloc] initWithObjectsAndKeys:
self.answer.text, @"text",
//else submit question text and topic id
self.question.text, @"question_text",
self.question.topic._id, @"topic_id",
shareFb, @"fbShare",
shareTwitter, @"twitterShare",
self.question.source,@"questionSource",
self.answer.videoId,@"youtube_id",
nil
];

最佳答案

使用可变字典,然后您可以添加额外的字段

NSMutableDictionary *params= [[NSMutableDictionary alloc] initWithObjectsAndKeys:
self.answer.text, @"text",
//if question id exists, submit question id only
self.question._id, @"question_id",
shareFb, @"fbShare",
shareTwitter, @"twitterShare",
self.question.source,@"questionSource",
self.answer.videoId,@"youtube_id",
nil
];

if(!(self.question._id == nil || [self.question._id isEqual:[NSNull null]]))
{
[params setObject:self.question.text forKey:@"question_text"];
[params setObject:self.question.topic._id forKey:@"topic_id"];
}

编辑评论 1

如果上面第一条语句中设置的任何参数可能为零,则需要更加小心

NSMutableDictionary *params= [[NSMutableDictionary alloc] init];
if (self.answer.text) {
[params setObject:self.answer.text forKey:@"text"];
}

• // all the params between self.answer.text and self.answer.videoId

if (self.answer.videoId) {
[params setObject:self.answer.videoId forKey:@"youtube_id"];
}
if(!(self.question._id == nil || [self.question._id isEqual:[NSNull null]]))
{
if(self.question.text) {
[params setObject:self.question.text forKey:@"question_text"];
}
if (self.question.topic._id) {
[params setObject:self.question.topic._id forKey:@"topic_id"];
}
}
}

您不能将 nil 对象设置为 key(即 [params setObject:nil forKey:@"key] 将崩溃)

关于objective-c - 删除用于提交到服务器的 NSDictionary Params 中的重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8783263/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com