I am implementing a shopping cart project on an iPad.
I have a class "productItem"
#import <Foundation/Foundation.h>
@interface ProductItem : NSObject
+(instancetype)createProductId:(NSString *)aId description:(NSString *)aDesc price:(int)aPrice;
@property(nonatomic, copy)NSString *productId;
@property(nonatomic, copy)NSString *description;
@property(nonatomic)int price;
@end
A class "CartItem"
@interface CartItem : NSObject
@property(nonatomic,weak)ProductItem *prodItem; @property(nonatomic)int quantity;
+(instancetype)createProdItem:(posProductItem *)aProdItem quantity:(int)aQuantity;
@end
I have another class "ProductStore". This class has 2 NSMUtableAray that stores productItems and cartItems:
@property(nonatomic)NSMutableArray *productItems;
@property(nonatomic)NSMutableArray *cartItems;
I implemented 2 ViewControllers, productSearchViewController and cartViewController. The cartViewController basically displays the elements in cartItems.
The functionalities of productSearchViewController are describe below:
productSearchViewController
products are displayed in UICollectionView. ProductItems retrieved from the web service are populated into ProductStore NSMutableArray "productItems"
[CartItem createProdItem:aProdItem quantity:1]; // here aProdItem is ProductItem *
(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString*)searchText
to query the web service for data. For each search, I will clear NSMutableArray "productItems" and re-populate it with the data from web service Because I clear UIMutableArray "productItems", the productItem in NSMutableArray "cartItems" gets deleted too. The cartItem elements are still there but the productItem in each cartItem element are empty: Product id, description and price are empty.
How should i go about solving this problem? should I copy ProductItem object into CartItems when a product is added into shopping cart?
The prodItem
is set to nil
because you have declared it as a weak
property in CartItem
in the following line:
@property(nonatomic,weak)ProductItem *prodItem;
You should use a strong
property if you need to use it in the CartItem
class even though it is removed from the productItems
array.
@property(nonatomic,strong)ProductItem *prodItem;
Although this should solve your problem, it does not actually make much sense to clear the productItems but keep the cartItems.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.