How to remove a specific object from an array

So I'm currently making a calorie tracker. In this app, you enter the recent meal you ate, and the amount of calories in that meal. Then you press the "add" button. This button will save the data to a TableView called HistoryTableViewController. To check if the person has left a textfield blank, I have 3 "if statement". One looks like this:

if ([[self.amountText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] < 1)
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning!" message:@"You have not entered the amount of Calories!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    [amountHistory removeObjectAtIndex:0];

}

There is one line of code that I know is wrong which is the

[amountHistory removeObjectAtIndex:0];

I don't necessarily want to remove the first object on the tableview, I just want to make sure that the item doesn't get added.

Thanks in advance.

EDIT:

I add an object to the array at the top of the if statements:

 total+= self.amountText.text.intValue;
 self.totalLabel.text = [NSString stringWithFormat:@"%d", total];
NSNumber *calorieNumber = [NSNumber numberWithInt:self.amountText.text.intValue];
NSString *foodString = nameOfTheFood.text;
NSString *historyString = [NSString stringWithFormat:@"%@ Calories in %@",       calorieNumber, foodString];
[amountHistory addObject:historyString];

Answers


Sounds like you are thinking about it from the wrong angle.

Instead of adding the item to your array and then removing it if it is invalid, you should ensure the item is only added when it is valid.

So in your method you would only add the item at the end, after all validation has passed. You would add early return's in your if statements if the any validation fails so that you don't reach the code that adds the item to the array


The answer to your subject:

How to remove a specific object from an array

is

[array removeObject:obj];

Note, this uses the isEqual message on the object to determine equality. If you want specific object equality, use removeObjectIdenticalTo: instead.

Source: Apple Docs on NSMutableArray


If you are looking to remove the last item in the array use:

[amountHistory removeLastObject];

But if your issue is that you don't want to add blank items to the array why not check if they are blank before adding them?


You can only remove objects from an array if you are using NSMutableArray. Have a read of the NSMutableArray Class Reference


Need Your Help

Integrating Smack with Android Studio project for chat application

android xmpp ejabberd smack asmack

I am trying to implement a chat messenger using ejabberd server and smack library but having a hard time to integrate all the jars and dependencies of smack. I am using android Studio.