My goal is to create an array of favorites in this class and add them to the array when the user clicks the favorite button. My problem is the for loop doesn't happen, meaning [arrayOfFavs count]
= 0. I understand the for the first time, but after I add an object, why wouldn't the count increase and the for loop take place?
-(IBAction)favbutton
{
bool *isThereAlready = true;
NSLog(@"start for loop");
for(int i = 0; i < [arrayOfFavs count]; i++)//problem here
{
if ([stateName isEqualToString: [[arrayOfFavs objectAtIndex:i] objectAtIndex:0]])
{
isThereAlready = false;
NSLog(@"sent to else");
}
NSLog(@"objects in arrayofStateFavs");
}
if(isThereAlready)
{
[checkedButton setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
NSArray *favArray = [NSArray arrayWithObjects:stateName,phoneName,faxName,addressName, nil];
[[NSNotificationCenter defaultCenter]
postNotificationName:@"favState"
object:favArray];
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTableViewNotification"
object:self];
[arrayOfFavs addObject:favArray];
}
else //unfavorite
{
[checkedButton setImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
NSArray *favDetails = [NSArray arrayWithObjects:stateName,phoneName,faxName,addressName, nil];
[[NSNotificationCenter defaultCenter]
postNotificationName:@"unfavState"
object:favDetails];
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTableViewNotification"
object:self];
for(int i = 0; i < [arrayOfFavs count]; i++)
{
if ([stateName isEqualToString: [[arrayOfFavs objectAtIndex:i] objectAtIndex:0]])
{
[arrayOfFavs removeObject:[arrayOfFavs objectAtIndex:i]];
i--;
}
}
}
}
Edit: This is not the same case as the question marked duplicate: the array is initialized and the for loop only loops once or none at all.
Edit 2: here is my code for initializing the array:
- (void)viewDidLoad
{
[super viewDidLoad];
// Set the Label text with the selected state
stateLabel.text = stateName;
phoneLabel.text = phoneName;
faxLabel.text = faxName;
addressLabel.text = addressName;
plistNum = [NSString stringWithFormat:@"tel:%@",phoneName];
arrayOfFavs = [[NSMutableArray alloc] init];//for this class
}