这里绝对是新手。我正在尝试使用几种不同的来源自学 Xcode。在我当前的类(class)中,我只是试图将字符串中的每个单词大写。出于某种原因,我没有使用 addObject 的选项,即使我已经求助于逐行复制书中的内容!这是我正在使用的代码,我只是将其输入到 ViewController.m 中。我没有接触过头文件。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *myString = @"How much wood could a woodchuck chuck";
NSArray *wordsInSentence = [myString componentsSeparatedByString:@" "];
NSLog(@"%@", wordsInSentence);
NSMutableArray *capitalizedWords = [[NSMutableArray alloc] init];
for (int word =0; word < [wordsInSentence count]; word++)
{
NSString *uncapitalizedWords = [wordsInSentence objectAtIndex:word];
NSString *capitalizedWords = [uncapitalizedWords capitalizedString];
[capitalizedWords addObject:capitalizedWords];
}
NSLog(@"%@", capitalizedWords);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
我的问题是 [大写词 addObject:大写词]; 当我开始输入时,它甚至没有在下拉框中显示 addObject 作为选项,我唯一的选项是 addObserver。
非常感谢任何帮助,谢谢
最佳答案
问题是您有两个具有相同名称的变量,capitalizedWords
。一个是可变数组,另一个是字符串。因此,当您在 for
循环中使用 capitalizedWords
时,它使用的是字符串再现。我建议重命名字符串变量,例如,替换:
NSString *uncapitalizedWords = [wordsInSentence objectAtIndex:word];
NSString *capitalizedWords = [uncapitalizedWords capitalizedString];
[capitalizedWords addObject:capitalizedWords];
与
NSString *uncapitalizedWord = [wordsInSentence objectAtIndex:word]; // renaming this isn't critical, but using singular case makes it more clear
NSString *capitalizedWord = [uncapitalizedWord capitalizedString]; // renaming this fixes the problem
[capitalizedWords addObject:capitalizedWord];
关于ios - xCode 不允许添加对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26202806/