iOS Objective C覆盖属性设置器

时间:2017-04-04 14:38:58

标签: android ios objective-c

在课堂上我有@property BOOL clearCookies;

我想设置它,以便在设置项目时我可以做一些额外的事情。

在我的代码中,我可以执行classInstance.clearCookies = YES;

之类的操作

然后在setter方法中,像android这样的java示例:

public void setClearCookies(boolean clearCookies) {
        _instance.clearCookies = clearCookies;
        _instance.doOtherThings();
    }

在Objective C中实现这一目标的最佳方法是什么?基本上我想设置布尔属性,但是还要做其他一些事情(实际上是从UIWebView清除cookie)

3 个答案:

答案 0 :(得分:2)

你可以这样做:

-(void)setClearCookies:(BOOL)clearCookies {
        _clearCookies = clearCookies;
       [self doOtherThings];
    }

答案 1 :(得分:2)

-(void)setClearCookies:(BOOL)clearCookies
{
    @synchronized(self)
    {
       _clearCookies = clearCookies;
       [self doOtherThings];
   } 
}

- (BOOL)clearCookies
{
   @synchronized (self)
   {
       return _clearCookies;
   }
}

答案 2 :(得分:1)

避免线程冲突(替代@synchronized())的另一种方法是使用Grand Central Dispatch(在大多数情况下比前者faster):

@property (assign, nonatomic) BOOL clearCookies;

// Later in code
static dispatch_queue_t clearCookiesQueue;

- (void)setClearCookies:(BOOL)clearCookies {
    [self initializeClearCookiesQueue];

    dispatch_async(clearCookiesQueue, ^{ // Note, this is "async"
        _clearCookies = clearCookies;
    });
}


- (BOOL)clearCookies {
    [self initializeClearCookiesQueue];

    __block BOOL clearCookies;
    dispatch_sync(clearCookiesQueue, ^{ // Note, this is "sync"
        clearCookies = _clearCookies;
    });

    // As "sync" waits until the operation is finished, you can define
    // your other operations here safely.
    [self doOtherStuff];

    return clearCookies;
}


/**
    Checks if the queue for the clearCookies property is initialized and,
    if it's not, initializes it.
*/
- (void)initializeClearCookiesQueue {
    if ( ! clearCookiesQueue ) {
        // We'll use a serial queue to avoid conflicts reading/writing the ivar
        clearCookiesQueue = dispatch_queue_create("com.yourapp.yourviewcontroller.someUniqueIdentifier", DISPATCH_QUEUE_SERIAL); // Note, this is a C string, not NSString
    }
}

如果您不关心线程,或者您不需要线程,只需覆盖您的setter即可:

- (void)setClearCookies:(BOOL)clearCookies {
    _clearCookies = clearCookies;
    [self doOtherStuff];
}