I get that error EXC_BAD_ACESS at the following line:
NSString *titleVarName = [[NSString alloc] initWithFormat:@"%@%@",@"occasionTitle",i];
Here is the for loop where the above code line is located:
for (i=0; i < count; ++i)
{
//Save the occasionS details to NSUserDefaults
NSString *titleVarName = [[NSString alloc] initWithFormat:@"%@%@",@"occasionTitle",i];
NSString *dateVarName = [[NSString alloc] initWithFormat:@"%@%@",@"occasionDate",i];
NSString *imageVarName = [[NSString alloc] initWithFormat:@"%@%@",@"occasionImage",i];
[[NSUserDefaults standardUserDefaults] setValue:[[[self displayedObjects] objectAtIndex:i]
title] forKey:titleVarName];
[[NSUserDefaults standardUserDefaults] setValue:[[[self displayedObjects] objectAtIndex:i]
date] forKey:dateVarName];
[[NSUserDefaults standardUserDefaults] setValue:[[[self displayedObjects] objectAtIndex:i]
imagePath] forKey:imageVarName];
//release
[titleVarName release];
[dateVarName release];
[imageVarName release];
[self dismissModalViewControll开发者_如何学编程erAnimated:YES];
}
Isn't ok to alloc objects and release them inside a for loop?
You need to use %d
or %i
specifier instead of %@
to specify an integer. If %@
is used with int then it will try to access the object at the address specified by the int. For example, if the value of i
is one then it is trying to access the object at address one which will cause a bad access.
NSString *titleVarName = [[NSString alloc] initWithFormat:@"%@%d",@"occasionTitle",i];
And also you don't need alloc
and release
here, though that is not the reason of bad access. You can use a convenience constructor.
NSString *titleVarName = [NSString stringWithFormat:@"occasionTitle%d", i];
// release not required
Do the same for dateVarName
and imageVarName
too.
Assuming i
is an int
, that line should be
NSString *titleVarName = [[NSString alloc] initWithFormat:@"%@%i",@"occasionTitle",i];
%@
is used for Cocoa objects, not primitives like an int, float or bool;
Use the %@
format specifier only for NSObject
objects.
As i
is an integer in your code, you have to use %d
or %i
for integers.
Moreover, there is no need to include the string using %@
, you can use the static string directly in your format string:
NSString *titleVarName = [[NSString alloc] initWithFormat:@"occasionTitle%i",i];
精彩评论