我在我的应用程序中制作购物车之类的概念时遇到了麻烦。我的 AppDelegate(名为 ST2AppDelegate)包含一个名为 myCart 的 NSMutableArray。我希望 RecipeViewController.m 将 NSString 对象传递给 myCart,但每次我将 NSString 传递给它并使用 NSLog 显示数组的内容时,它总是为空的。
谁能告诉我我做错了什么?我已经在这段代码上工作了好几天,有一行代码我根本不明白发生了什么(在 RecipeViewController.m 中,标记为这样)。
任何帮助将不胜感激......我只是一个初学者。以下是相关类:
ST2AppDelegate.h:
#import <UIKit/UIKit.h>
@interface ST2AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) NSMutableArray* myCart;
- (void)addToCart:(NSString*)item;
- (void)readCartContents;
@end
ST2AppDelegate.m:
#import "ST2AppDelegate.h"
@implementation ST2AppDelegate
@synthesize myCart;
// all the 'applicationDid...' methods...
- (void)addToCart:(NSString *)item
{
[self.myCart addObject:item];
}
- (void)readCartContents
{
NSLog(@"Contents of cart: ");
int count = [myCart count];
for (int i = 0; i < count; i++)
{
NSLog(@"%@", myCart[count]);
}
}
@end
RecipeDetailViewController.h:
#import <UIKit/UIKit.h>
#import "ST2AppDelegate.h"
@interface RecipeDetailViewController : UIViewController
@property (nonatomic, strong) IBOutlet UILabel* recipeLabel;
@property (nonatomic, strong) NSString* recipeName;
@property (nonatomic, strong) IBOutlet UIButton* orderNowButton;
- (IBAction)orderNowButtonPress:(id)sender;
@end
RecipeDetailViewController.m:
#import "RecipeDetailViewController.h"
@implementation RecipeDetailViewController
@synthesize recipeName;
@synthesize orderNowButton;
// irrelevant methods...
- (IBAction)orderNowButtonPress:(id)sender
{
// alter selected state
[orderNowButton setSelected:YES];
NSString* addedToCartString = [NSString stringWithFormat:@"%@ added to cart!",recipeName];
[orderNowButton setTitle:addedToCartString forState:UIControlStateSelected];
// show an alert
NSString* addedToCartAlertMessage = [NSString stringWithFormat:@"%@ has been added to your cart.", recipeName];
UIAlertView* addedToCartAlert = [[UIAlertView alloc] initWithTitle:@"Cart Updated" message:addedToCartAlertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[addedToCartAlert show];
// add to cart (I don't understand this, but it works)
[((ST2AppDelegate*)[UIApplication sharedApplication].delegate) addToCart:recipeName];
// read cart contents
[((ST2AppDelegate*)[UIApplication sharedApplication].delegate) readCartContents];
}
@end