objective c - How to make a boolean both static and __block? in iOS? -
bool _hintexist; - (void)shownotreachable { if (_hintexist) { return; } nslog(@"show hint"); dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(3 * nsec_per_sec)), dispatch_get_main_queue(), ^{ _hintexist = no; }); } the code above fine. there button trigger method. actually, don't need _hintexist global variable. want make bool _hintexist in method.however, when tried add both static , __block in front of bool _hintexist. there compile error. amazed change _hintexist in block if made global variable. explain why? , what's difference if add static before bool _notreachablehintexist, global variable in code?
__block scope modifier local variable allows block modify value of local variable declared in outer scope.
your _hintexist variable isn't local variable. it's global. there no need __block modifier. block has access global variable other piece of code in same file.
if add static _hintexist variable, still global scoped file. , block, other code in file, can still access , modify file global variable.
another option make _hintexist variable local static variable this:
- (void)shownotreachable { static bool _hintexist = false; if (_hintexist) { return; } nslog(@"show hint"); dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(3 * nsec_per_sec)), dispatch_get_main_queue(), ^{ _hintexist = no; }); } this works assuming want. variable scoped method being static means value independent of specific instance of class. again, being static means don't need __block modifier. it's global inside method.
btw - minor note on common naming conventions. don't use leading underscore variables except instance variables.
update based on andy's second comment below answer:
it seems want use instance variable since want each instance of class start own false value _hintexist.
add ivar @implementation block:
@implementation whateverclassthisis { bool _hintexist; } and updated shownotreachable method:
- (void)shownotreachable { if (_hintexist) { return; } nslog(@"show hint"); dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(3 * nsec_per_sec)), dispatch_get_main_queue(), ^{ _hintexist = no; }); } like globals , statics, instance variable doesn't need __block qualifier. and, default, _hintexist have initial value of false.
Comments
Post a Comment