I have a shopping cart in my app. I also have a UIBarButton called "Empty Cart". Im implementing functionality for this button. However, Im running into some problems. My Cart is a Singleton Data Object. What I want to do is when the user presses "Empty Cart", all the objects and variable values in the cart should be released and/or made 0.
I have an "emptyCart" method implemented in my ViewController which calles an "emptyCart" method of the CartSingleton in turn. My problem is as shown below the release calls to the various objects are not releasing the objects, because when I print the contents of the Cart after running "empty cart", i can still see all the items in the Cart. Does the release message not take effect right away? How can I instantly release all the objects in my Cart then?
Code- "Empty Cart" in Singleton:
-(void)emptyCart
{
if (self.selectedLocation != NULL)
{
[self.selectedLocation release];
self.locationSelected = false;
}
if (self.foodItemsArray != NULL)
{
for (int i = 0; i < [self.foodItemsArray count]; i++)
{
FoodItem *temp = [self.foodItemsArray objectAtIndex:i];
if (temp.sidesArray != NULL)
{
[temp.sidesArray release];
}
}
[self.foodItemsArray release];
}
if (self.drinkItemsArray != NULL)
{
[self.drinkItemsArray re开发者_如何转开发lease];
}
if (self.otherItemsArray != NULL)
{
[self.otherItemsArray release];
}
if (self.customerInfo != NULL)
{
[self.customerInfo release];
}
self.numFoodItems = 0;
//self.totalTaxPercent = 0;
self.foodItemsTotalCost = 0;
self.drinkItemsTotalCost = 0;
self.otherItemTotalCost = 0;
self.totalCostOfAllItems = 0;
self.totalTaxesAmount = 0;
self.totalChargesWithTaxes = 0;
self.gratuity = 0;
self.miscCharges = 0;
Releasing releases right away -- meaning, it reduces the retain count, and if the retain count is 0, then the object is deallocated.
Your problem is that you are holding onto the objects -- not setting the variables to nil after you are done with them.
I am also worried that you are releasing too many times
- Arrays release their elements when they are released
retained @properties will release the object they are set to if you set them to nil - you should be clearing them like so:
self.customerInfo = nil;
So, watch out. It looks like right now you are accessing released objects -- which will crash eventually. Over releasing will also cause problems.
To try to find out these issues
- Use Build and Analyze and fix the errors it reports
Turn on Zombies and see if you are accessing released objects
http://www.loufranco.com/blog/files/debugging-memory-iphone.html
release
does nothing more than decrement the retain count on an object. The runtime, when it observes that the retain reaches zero, will then call the dealloc
method of your object.
Therefore, if you still have objects in there, this means that other objects have placed retain on the object (increasing its retain count) meaning that they will stick around.
精彩评论