0

Apple recommend "Do not Use Accessor Methods in Initializer Methods and dealloc" with this document: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html

If I want to set up the block in the initializer methods, block references to the property, how I write better code?

typedef void(^customBlock)();

@interface CustomObject : NSObject
@property (nonatomic, strong) NSString *string;
@property (nonatomic, copy) customBlock customBlock1;
@property (nonatomic, copy) customBlock customBlock2;
@end

@implementation CustomObject

- (instancetype)init {
    self = [super init];
    if (self) {
        __weak __typeof(self) weakSelf = self;

        _customBlock1 = ^ {
            __typeof(self) strongSelf = weakSelf;
            strongSelf -> _string = @"string by iVar";
        };

        _customBlock2 = ^{
            weakSelf.string = @"string by accessor";
        };
    }
    return self;
}

@end
joe
  • 2,468
  • 2
  • 12
  • 19
Lavare
  • 89
  • 2
  • 4
  • Do not follow that "recommendation". It is meaningless. – Amin Negm-Awad Aug 02 '16 at 20:23
  • @AminNegm-Awad I understand what you mean. I wrote the demo to this issue for ["Do not Use Accessor Methods in Initializer Methods and dealloc"](https://github.com/yangcaimu/UseAccessorMethodsInInitializerMethodsAndDeallocDemo). – Lavare Aug 08 '16 at 05:34
  • You misunderstood me: *Apple's* recommendation is meaningless. This is a long discussion and one can be pretty sure that it will lead to dozens of comments. – Amin Negm-Awad Aug 08 '16 at 05:37

1 Answers1

0
_customBlock1 =[ ^ {
        __typeof(self) strongSelf = weakSelf;
        strongSelf -> _string = @"string by iVar";
    } copy];

This can reach the effect of calling the setter method, so avoiding the side effects of using accessor methods in Initializer methods.

hwris
  • 61
  • 5
  • Please add an explanation. – Amin Negm-Awad Aug 02 '16 at 20:22
  • Is it necessary to add `copy` message? From clang's [Objective-C Automatic Reference Counting](http://clang.llvm.org/docs/AutomaticReferenceCounting.html#blocks) documentation: The optimizer may remove such copies when it sees that the result is used only as an argument to a call. Detail: [Should I still copy/Block_copy the blocks under ARC?](http://stackoverflow.com/a/23352604/3097963) – Lavare Aug 08 '16 at 05:28
  • There is no call in his code. It is an assignment. As you can read in the answer that is linked by you, a property should be a copy property. Therefore the assignment should be a copy assignment. This is one of the examples that let me comment the Q as I did. – Amin Negm-Awad Aug 08 '16 at 05:44