NSMutableArray计数总是返回零 [英] NSMutableArray count always returns zero

查看:159
本文介绍了NSMutableArray计数总是返回零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试图循环访问数据库结果,从这些结果中创建对象结果,并将对象添加到NSMutableArray。我已通过NSLog调用验证数据正确地从数据库读取并复制到对象,但NSMutableArray 始终的计数返回0。



这是代码的精髓:

  while([rs next]){

Kana * htemp = [Kana alloc];

htemp.content = [rs stringForColumn:@hiragana];
[hiragana addObject:htemp];

}
NSLog(@Hiragana包含%d个对象,[平假名计数]);

Kana派生自NSObject,平假名是NSMutableArray的一个实例。



我相信这是一个菜鸟的错误,我希望有人能直接让我。 TIA! :)

解决方案

我的猜测,从你发布的代码判断,你可能没有正确分配数组。创建对象时,还需要对其进行初始化。因此,这个:

  Kana * htemp = [Kana alloc]; 

应为:

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

所有对象都需要以这种方式初始化。 m正确,你没有初始化你的数组,那么你的创建需要从这里:

  NSMutableArray * hiragana = [NSMutableArray alloc]; 

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

出于优化的原因,如果你有任何想法,你可能持有的对象:

  [[NSMutableArray alloc] initWithCapacity:someNumber]; 


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 objects to an NSMutableArray. I've verified via NSLog calls that the data is being correctly read from the database and copied to the object, but the count for the NSMutableArray always returns 0.

Here's the essence of the code:

while ([rs next]) {

    Kana *htemp = [Kana alloc];

    htemp.content = [rs stringForColumn:@"hiragana"];
    [hiragana addObject:htemp];

}
NSLog(@"Hiragana contains %d objects", [hiragana count]);

Kana is derived from NSObject, and hiragana is an instance of NSMutableArray.

I'm sure this is a rookie mistake, and I hope someone can set me straight. TIA! :)

解决方案

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

这篇关于NSMutableArray计数总是返回零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆