0

我正在编写此代码来为我的 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
4

1 回答 1

0

你没有说你遇到了什么问题。我认为这与您尝试写入应用程序包目录有关。在文件系统编程指南中不鼓励这样做。您应该阅读它的“文件系统基础”和“访问文件和目录”章节。

一般要点是您应该在第一次启动时将“Objects.plist”复制到“Library”文件夹,然后从那里读取和写入。

于 2012-08-10T23:27:06.513 回答