xCode不允许使用addObject

时间:2014-10-05 13:01:01

标签: ios objective-c cocoa-touch

绝对是初学者。我试图用几种不同的来源自学Xcode。我目前的教训是,我只是试图将字符串中的每个单词大写。出于某种原因,我没有选择使用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

我的问题在于      [capitalizedWords addObject:capitalizedWords]; 当我开始输入时,它甚至不会在下拉框中显示addObject作为选项,我唯一的选择是addObserver。

非常感谢任何和所有帮助,谢谢

2 个答案:

答案 0 :(得分:3)

问题是您有两个名称相同的变量capitalizedWords。一个是可变数组,另一个是字符串。因此,当您在capitalizedWords循环中使用for时,它正在使用字符串再现。我建议重命名字符串变量,例如,替换:

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];

答案 1 :(得分:0)

问题是您将字符串命名为与数组相同。 尝试更改

NSString *capitalizedWords = [uncapitalizedWords capitalizedString];
[capitalizedWords addObject:capitalizedWords];

为:

NSString *capitalizedWordsString = [uncapitalizedWords capitalizedString];
[capitalizedWords addObject:capitalizedWordsString];

当您声明与数组同名的字符串时,您将对数组进行阴影处理,Xcode会将capitalizedWords视为字符串,而不是数组。这就是为什么它没有为您提供addObject方法。