【问题标题】:cant store objects at NSMutableArray无法将对象存储在 NSMutableArray
【发布时间】:2011-10-27 13:13:41
【问题描述】:

我的代码可以像这样扫描并返回NSString

NSString *GetText = [[NSString alloc] init];
NSString *ScannedText;
NSScanner *TheScanner = [NSScanner scannerWithString:somLongString];
int start=0;
int index=0;
int ObjectCount;
char c;
for (int i = 0; i < [somLongString length] ; i++) {
    c = [somLongString characterAtIndex:i];
    if (c == '=') {
        start = i+1;
        [TheScanner setScanLocation:start];
        [TheScanner scanUpToString:@"&" intoString:&GetText];
        NSLog( @"%@",GetText);
        [UserValuesObject insertObject:GetText  atIndex:index];
        NSLog(@"%@",[UserValuesObject objectAtIndex:index]);
        index++;
    }
}

现在我想将每次创建的GetText 对象添加到数组中。当我尝试打印第一个时:

NSLog(@"%@",GetText); 

有效!但是当我试图将它添加到对象然后打印(用于调试)时,我在每次打印日志时都得到null

NSLog(@"%@",[UserValuesObject objectAtIndex:index]);

有什么想法吗?

【问题讨论】:

  • 什么是[UserValuesObject GetText atIndex:index];
  • 抱歉代码是这样的 [UserValuesObject insertObject:GetText atIndex:index];
  • 请首先包含您创建UserValuesObject 的代码。另外,作为一般说明,objective-c 中的变量名以小写字母开头,类名以大写字母开头。
  • 好的,我已经尝试更改它但仍然无法正常工作
  • @orazran 你能显示你分配/初始化UserValuesObject的代码吗?

标签: objective-c xcode nsmutablearray nsarray


【解决方案1】:

您可能没有正确(或根本没有)初始化您的数组,试试这个(包括语法改进):

NSString *getText = [NSString string];
NSScanner *scanner = [NSScanner scannerWithString:someLongString];
NSUInteger start = 0;
NSUInteger index = 0;
NSMutableArray *userValuesObject = [NSMutableArray array];
//  You should save the length of someLongString before starting the loop 
//   so that each iteration doesn't have to call length to see if i has 
//   reached length yet
for (int i = 0, len = [someLongString length]; i < len; ++i) {
    if ([somLongString characterAtIndex:i] == '=') {
        [scanner setScanLocation:(i + 1)];
        [scanner scanUpToString:@"&" intoString:getText];
        NSLog(@"%@", GetText);
        [userValuesObject insertObject:getText atIndex:index];
        NSLog(@"%@", [userValuesObject objectAtIndex:index]);
        ++index;
    }
}

来自NSMutableArray Docs

insertObject:atIndex:

参数

anObject - 添加到数组内容的对象。这个值必须 不为零。

重要提示:如果 anObject 为 nil,则引发 RaisesanNSInvalidArgumentException。

index - 数组中插入对象的索引。这 value 不能大于数组中元素的个数。

重要提示:如果索引大于数组中的元素数,则引发 NSRangeException。

如果 index 已被占用,则 index 及之后的对象是 通过在它们的索引上加 1 来腾出空间。请注意,NSArray 对象不像 C 数组。也就是说,即使您指定了大小 创建数组时,指定的大小被视为“提示”; 数组的实际大小仍然是 0。这意味着你不能 在大于当前计数的索引处插入对象 大批。例如,如果一个数组包含两个对象,它的大小是 2, 因此您可以在索引 0、1 或 2 处添加对象。索引 3 是非法的,并且 越界;如果您尝试在索引 3 处添加对象(当大小 数组的个数为 2),NSMutableArray 引发异常。

【讨论】:

    【解决方案2】:

    我认为 NSMutableArray, UserValuesObject 为 nil,因此不允许您设置数组的任何对象。

    在进入 for 循环之前尝试检查数组是否为 nil。

    if (UserValuesObject == nil) {
        UserValuesObject = [NSMutableArray array];
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 2012-05-31
      • 2011-08-22
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 2011-02-28
      相关资源
      最近更新 更多