-1

重複の可能性:
plistに正常に書き込む方法は?

UISwitchのブール状態(trueまたはfalse)をPlistファイルに単純に書き込みたいと思います。

これは私がすでに得たものですが、値はplistで変更されません:

.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController {


    IBOutlet UISwitch *mySwitch;

}

-(IBAction)changeThingsInPlist:(id)sender;

@end

.m

#import "ViewController.h"

BOOL changeThing;
#define PLIST_PATH @"/var/mobile/Library/Preferences/com.myname.plistname.plist"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];


    changeThing = [[[NSDictionary dictionaryWithContentsOfFile:PLIST_PATH]valueForKey:@"changeThing"]boolValue];

}

-(IBAction)changeThingsInPlist:(id)sender {

    if (mySwitch.on = YES) {
        changeThing = true;
    }
    else {
        changeThing = false;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

uiswitchを切り替えて、plistファイルの値(trueまたはfalse)を変更したいだけです。

NSUserDefaultsを使用する必要がありますか?:)

私はそれを読みましたが、NSUserDefaultsでplistパスを設定する方法を知りませんでした

ありがとうございました

4

1 に答える 1

0

NSStringを作成し、UISwitchのブール値に基づいてその値を設定する必要があると言えます。

NSString *valueOfSwitch;
if (mySwitch.on == YES){
valueOfSwitch = [NSString stringWithFormat:@"ON"];
}
else {
valueOfSwitch = [NSString stringWithFormat:@"OFF"];
}

次に、その文字列をNSUserDefaultsにそのように配置する必要があります。

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:valueOfSwitch forKey:@"switchValue"];   //remember this for retrieving
[defaults synchronize];

次に、この文字列を取得するには、これを行います。

NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *switchString = [data objectForKey:@"switchValue"]; //same key that you used for saving
[data synchronize];

そこから、その文字列を使ってやりたいことが何でもできます。

于 2012-08-07T19:55:34.017 に答える