NSMutableArray 初始化

发布于 2024-11-24 04:11:14 字数 389 浏览 1 评论 0原文

我对 Objective C 很陌生。我读过很多相关主题但无法找到解决方案。 我正在使用 NSMutableArray,并通过以下模式分配和初始化:

events = [[NSMutableSet alloc] init];

是吗?通过这种方式,我可以毫无问题地将对象添加到数组中,但是当我迭代或读取时,我得到了SIGABRT:无法识别的选择器发送到实例。尝试了几次修改,我能得到的最好结果是另一个例外:EXC_BAD_ADDRESS。我用来读取数组的行是:

Event *event = [events objectAtIndex:1];

提前致谢。

初级

I'm very newby on Objective C. I've read a lot of topics related but couldn't get solution.
I'm using a NSMutableArray, and alloc and init by the following mode:

events = [[NSMutableSet alloc] init];

Is it right? In this way, I can add objects to the array without problems, but when I iterate or to read, I got SIGABRT: unrecognized selector sent to instance. Attempting several modifications, the best I could get was another exception: EXC_BAD_ADDRESS. The line I'm using to read the array is:

Event *event = [events objectAtIndex:1];

Thanks in advance.

Junior

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

滥情哥ㄟ 2024-12-01 04:11:42
events = [[NSMutableArray alloc] init];
[events addObject:event1];
[events addObject:event2]

for (int i = 0; i < [events count]; i++) {
    Event *event = (Event)[events objectAtIndex:i];
    NSLog("Event: %@", event);
    [event release];
}

像这样。

events = [[NSMutableArray alloc] init];
[events addObject:event1];
[events addObject:event2]

for (int i = 0; i < [events count]; i++) {
    Event *event = (Event)[events objectAtIndex:i];
    NSLog("Event: %@", event);
    [event release];
}

Like this.

2024-12-01 04:11:41

这中间发生了什么?请记住,数组是零索引的;那里可能没有两个元素。尝试使用计数方法。

What's going on in between? Remember that arrays are zero-indexed; there may not be two elements in there. Try using the count method.

初见你 2024-12-01 04:11:40

您说过您正在使用 NSMutableArrays,但随后初始化了一个集合,请尝试使用:

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

集合不响应 objectAtIndex,因为它们是无序的。如果你想要一个集合中的一个对象,你可以调用它的anyObject。或者您可以使用枚举来遍历所有对象。
例如

id obj=[events anyObject];

for(id obj in events){
    NSLog(@"%@",obj);
}        

you have said you are using NSMutableArrays, but then initialised a set, try using:

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

sets don't respond to objectAtIndex, because they are unordered. if you want an object out of a set, you can call anyObject on it. or you can use enumeration to go through all objects.
eg

id obj=[events anyObject];

or

for(id obj in events){
    NSLog(@"%@",obj);
}        
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文