我正在编写此代码来为我的 DetailViewController 中的 UIButton 设置默认状态,这取决于带有字典的 plist 数组中的字符串值。这工作正常(在 viewDidLoad 中)。
然后我想在 favoriteButtonPressed 时写入 plist,但这不起作用。我认为代码中的某些内容是错误的。你能帮我改正吗?
DetailViewController.h
#import <UIKit/UIKit.h>
@interface DetailViewController : UIViewController
//The selectedObject property is recieved through segue from TableViewController
@property (nonatomic, strong) NSMutableArray *selectedObject;
@property (nonatomic, assign) BOOL favoriteButtonSelected;
@property (weak, nonatomic) IBOutlet UIButton *favoriteButton;
-(IBAction)favoriteButtonPressed:(id)sender;
@end
细节视图控制器.m
#import "DetailViewController.h"
@interface DetailViewController ()
@end
@implementation DetailViewController
@synthesize selectedObject;
@synthesize favoriteButtonSelected;
@synthesize favoriteButton;
- (void)viewDidLoad
{
[super viewDidLoad];
if ([[selectedObject valueForKey:@"Favorite"] isEqual:@"Yes"]) {
[favoriteButton setImage:[UIImage imageNamed:@"favoritedItem.png"] forState:UIControlStateSelected | UIControlStateHighlighted];
[favoriteButton setSelected:YES];
[favoriteButton setHighlighted:YES];
favoriteButtonSelected = 1;
} else {
[favoriteButton setImage:[UIImage imageNamed:@"notFavorite.png"] forState:UIControlStateNormal];
[favoriteButton setSelected:NO];
[favoriteButton setHighlighted:NO];
favoriteButtonSelected = 0;
}
}
//Action to write to plist
-(IBAction)favoriteButtonPressed:(id)sender
{
NSString *path = [[NSBundle mainBundle]
pathForResource:@"Objects" ofType:@"plist"];
if (favoriteButtonSelected == 0) {
[sender setSelected:YES];
[sender setHighlighted:YES];
favoriteButtonSelected = 1;
[sender setImage:[UIImage imageNamed:@"favoritedItem.png"] forState:UIControlStateSelected | UIControlStateHighlighted];
[selectedObject setValue:@"Yes" forKey:@"Favorite"];
[selectedObject writeToFile:path atomically:YES];
} else {
[sender setSelected:NO];
[sender setHighlighted:NO];
favoriteButtonSelected = 0;
[sender setImage:[UIImage imageNamed:@"notFavorite.png"] forState:UIControlStateNormal];
[selectedObject setValue:@"No" forKey:@"Favorite"];
[selectedObject writeToFile:path atomically:YES];
}
}
@end