Why did happen EXC_BAD_ACCESS and SIGABRT when set integer? [closed]

寵の児 提交于 2019-12-13 09:14:19

问题


I wrote code.

I want to save integer using nsuserdefault.

But this code happen EXC_BAD_ACCESS and SIGABRT.


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    [self desave:[newys integerValue] :[newms integerValue]];
    ...
}

...

- (void)desave:(NSInteger*)year :(NSInteger*)month//←EXC BAD ACCESS happened on this row.
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setInteger:year forKey:@"year"];//←SIGABRT happened on this row.

    [defaults synchronize];
}

回答1:


Based on your desave method signature, you're passing an NSInteger* as an argument where an NSInteger is expected. NSInteger is not an object derived from NSObject, it's a primitive.




回答2:


The problem is caused by the needless pointers being used for the NSInteger parameters.

Change:

- (void)desave:(NSInteger*)year :(NSInteger*)month

to:

- (void)desave:(NSInteger)year :(NSInteger)month

NSInteger is not a class type.

You should also name your method a little better. Right now the name is desave::. It would be better if it was:

- (void)desaveYear:(NSInteger*)year month:(NSInteger*)month

Now the name is desaveYear:month:.

And now you can call it with:

[self desaveYear:[newys integerValue] month:[newms integerValue]];



回答3:


You are passing a pointer to an NSInteger. The simplest way to solve this is:

- (void)desave:(NSInteger)year :(NSInteger)month
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:year forKey:@"year"];
    [defaults synchronize];
}



回答4:


On your method

- (void)desave:(NSInteger*)year :(NSInteger*)month

You are sending both year and month variables pointers. This sends the memory addresses instead. Try with this instead

- (void)desave:(NSInteger)year :(NSInteger)month
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:year forKey:@"year"];
    [defaults synchronize];
}


来源:https://stackoverflow.com/questions/18338800/why-did-happen-exc-bad-access-and-sigabrt-when-set-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!