将对象添加到 NSArray 时程序崩溃

发布于 2025-01-04 02:10:55 字数 802 浏览 2 评论 0原文

我设置了以下IBAction

#define FAVORITES_KEY @"GraphViewController.Favorites"
- (IBAction)addToFavorites:(id)sender {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *favorites = [defaults objectForKey:FAVORITES_KEY];
    if (!favorites) favorites = [NSMutableArray array];
    [favorites addObject:self.program];
    [defaults setObject:favorites forKey:FAVORITES_KEY];
    [defaults synchronize];
}

第一次调用此操作时一切正常,该对象被添加到我的数组中并保存到NSUserDefaults,没有问题,之后第一次调用它在添加到 favorites 数组时会抛出异常,如果我尝试跨过中断,它会说:

Single stepping until exit from function objc_exception_throw, 
which has no line number information.

Catchpoint 3 (exception thrown).

有人遇到类似问题或可能知道发生了什么吗?

I have the following IBAction set up:

#define FAVORITES_KEY @"GraphViewController.Favorites"
- (IBAction)addToFavorites:(id)sender {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *favorites = [defaults objectForKey:FAVORITES_KEY];
    if (!favorites) favorites = [NSMutableArray array];
    [favorites addObject:self.program];
    [defaults setObject:favorites forKey:FAVORITES_KEY];
    [defaults synchronize];
}

The first time this action is called it all works well, the object is added to my array and saved to NSUserDefaults without a problem, after that first call it will throw an exception when adding to the favorites array, if I try to step over the break it will say this:

Single stepping until exit from function objc_exception_throw, 
which has no line number information.

Catchpoint 3 (exception thrown).

Anyone had a similar issue or might know what's happening?

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

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

发布评论

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

评论(1

转身以后 2025-01-11 02:10:55

NSUserDefaults 返回一个不可变数组,因此您需要对其进行转换:

NSMutableArray *favorites = [[defaults objectForKey:FAVORITES_KEY] mutableCopy];
if (!favorites) favorites = [NSMutableArray new];
...
[favorites release];

NSUserDefaults returns an immutable array, so you need to convert it:

NSMutableArray *favorites = [[defaults objectForKey:FAVORITES_KEY] mutableCopy];
if (!favorites) favorites = [NSMutableArray new];
...
[favorites release];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文