10

BOOL や NSIntegers などの単純な変数にオブザーバーを追加して、いつ変化するかを確認することはできますか?

ありがとう!

4

4 に答える 4

22

値が変更されたときにキーが通知されることを確認します。データ型は何でもかまいません。Objective-C プロパティ (.h ファイルで @property を使用) として定義されているものについては、これですぐに使用できるので、View Controller に追加する BOOL プロパティを監視する場合は、次のようにします。

myViewController.h で:

@interface myViewController : UIViewController {
    BOOL      mySetting;
}

@property (nonatomic)    BOOL    mySetting;

myViewController.m で

@implementation myViewController

@synthesize mySetting;

// rest of myViewController implementation

@end

otherViewController.m で:

// assumes myVC is a defined property of otherViewController

- (void)presentMyViewController {
    self.myVC = [[[MyViewController alloc] init] autorelease];
    // note: remove self as an observer before myVC is released/dealloced
    [self.myVC addObserver:self forKeyPath:@"mySetting" options:0 context:nil];
    // present myVC modally or with navigation controller here
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == self.myVC && [keyPath isEqualToString:@"mySetting"]) {
        NSLog(@"OtherVC: The value of self.myVC.mySetting has changed");
    }
}
于 2011-04-11T18:29:50.290 に答える
5

プロパティが変更された場合、「変更」辞書から INT または BOOL 値を取得する方法。

次の方法で簡単に実行できます。

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if ([keyPath isEqualToString:@"mySetting"])
    {
        NSNumber *mySettingNum = [change objectForKey:NSKeyValueChangeNewKey];
        BOOL newSetting = [mySettingNum boolValue];
        NSLog(@"mySetting is %s", (newSetting ? "true" : "false")); 
        return;
    }

    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
于 2014-02-04T23:21:06.403 に答える
1

はい; 唯一の要件は、それらの変数が発生するオブジェクトがそれらのプロパティのキー値に準拠していることです。

于 2011-04-11T15:58:37.253 に答える
-2

それらがオブジェクトのプロパティである場合は、はい。

それらがプロパティでない場合は、いいえ。

于 2011-04-11T15:58:18.213 に答える