Why did happen EXC_BAD_ACCESS and SIGABRT when set

2019-09-21 11:36发布

问题:

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