NSMutableArray count always returns zero

前端 未结 3 1599
無奈伤痛
無奈伤痛 2021-01-12 13:09

I\'m sure I\'m doing something silly, but this is driving me crazy.

I\'m trying to loop through database results, create objects from those results, and add the obje

相关标签:
3条回答
  • 2021-01-12 13:12

    A few things:

    1. What happens if you put an NSLog call inside of the while loop? Verify that loop iterations are actually happening before blaming it on the array.
    2. Where are you creating the array hiragana? If you are doing it incorrectly for some reason and the array is nil, it might cause problems like this.
    3. If you do not have garbage collection on, be sure to do [htemp release] after adding it to the loop. addObject retains and each added item will leak from the loop. Again, this is only relevant if garbage collection is off.

    It's most likely either you aren't created the array correctly or rs doesn't contain what you expect it to contain, and so [rs next] isn't getting called ever (if rs is nil, for example, no iterations of this loop would execute and you wouldn't have any sort of error).

    0 讨论(0)
  • Another common cause (not in your case, as it turns out, but generally) is forgetting to even allocate the array. If you haven't created an array yet, you're sending that count message to nil, so the result will always be 0.

    0 讨论(0)
  • 2021-01-12 13:21

    My guess, judging from the code you posted, is that you probably aren't allocating your array properly. When creating objects, you need to initialize them as well. Therefore, this:

    Kana *htemp = [Kana alloc];
    

    Should be:

    Kata *temp = [[Kana alloc] init];
    

    All objects need to be initialized this way. Thus, if I'm correct and you haven't initialized your array, then your creation needs to go from this:

    NSMutableArray *hiragana = [NSMutableArray alloc];
    

    to this:

    NSMutableArray *hiragana = [[NSMutableArray alloc] init];
    

    For optimization reasons, you should probably also specify an initial capacity as well if you have any idea how many objects you might hold:

    [[NSMutableArray alloc] initWithCapacity:someNumber];
    
    0 讨论(0)
提交回复
热议问题