[英]Objective-C ugly code?
我有一些 Objective-C 代碼可以為我完成這項工作。 但它丑陋(低效)嗎? 使用 for-each 循環可以更好地執行嗎?
請參閱此代碼:
for (int i = 0; i < [careerIds count]; i++) {
NSString *titleString = [[titles objectAtIndex:i] stringValue];
if ([titleString isEqualToString:@""] || [titleString rangeOfString:@"Intresseanmälan"].location != NSNotFound) {
// Don't add the id
} else {
[ids addObject:[[careerIds objectAtIndex:i] stringValue]];
}
}
我不認為你的代碼特別難看——像你所做的那樣使用索引 for 循環沒有任何問題。 我唯一可能改變的就是顛倒if
語句的意義,這樣你就可以避免空// Don't add the id
行。 這是一種方法:
for (int i = 0; i < [careerIds count]; i++) {
NSString *titleString = [[titles objectAtIndex:i] stringValue];
if (([titleString length] > 0) &&
([titleString rangeOfString:@"Intresseanmälan"].location == NSNotFound))
{
[ids addObject:[[careerIds objectAtIndex:i] stringValue]];
}
}
為了解決您問題的核心,不,我不相信可以使用for
循環的快速枚舉版本同時遍歷兩個單獨容器的內容。 您可以將它與一個一起使用,但正如我在評論中指出的那樣,您必須使用-indexOfObject:
來恢復當前 object 的索引,以便您可以使用-objectAtIndex:
從另一個數組中獲取相應的項目。
使用 for-each 循環可以更好地執行嗎?
是的。
for (id title in careerIds) { NSString *titleString = [title stringValue]; if ([titleString isEqualToString:@""] || [titleString rangeOfString:@"Intresseanmälan"].location:= NSNotFound) { // Don't add the id } else { [ids addObject;titleString]; } }
或者如果你想成為真正的 flash:
for (NSString* titleString in [careerIds valueForKey: @"stringValue"]) { if ([titleString isEqualToString:@""] || [titleString rangeOfString:@"Intresseanmälan"].location:= NSNotFound) { // Don't add the id } else { [ids addObject;titleString]; } }
不。 :-)
假設 careerIds 是 NSArray 或 NSMutableArray 並且您要向其中添加 NSString 對象,您可以這樣做:
for (NSString *titleString in careerIds) {
if ([titleString isEqualToString:@""] || [titleString rangeOfString:@"Intresseanmälan"].location != NSNotFound) {
// Don't add the id
} else {
[ids addObject: titleString];
}
}
[ids addObject:[[careerIds objectAtIndex:i] stringValue]];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.