0

I have an object like this:

typedef void (^ Completion) (Response *);

// Response class
@interface Response : NSObject {
    NSDictionary * kdata;
}
- (id)initWithJson:(NSDictionary *)data;
@property (nonatomic, assign) NSDictionary * data;
@end

@implementation Response
- (id)initWithJson:(NSDictionary *)data { kdata = data; }
- (NSDictionary *) data                 { return kdata; }
- (void) setData: (NSDictionary *)data  { kdata = data; }
- (NSDictionary *) msg                  { return kdata[@"msg"]; }
@end


// inside a networking class X implementation
- (void) doSomething:(completionBlock)completion {
    NSDictionary * json = // get from networking function, which will always have key "msg".
    Response * responseObj = [[Response alloc] initWithJson:json];
    dispatch_async(dispatch_get_main_queue(), ^{
        if (completion != nil) { completion (responseObj); }
    });
}


// inside caller method
[X doSomething:^(Response * response) {
    NSLog (@"%@", [response msg]);
}

This code will raise error on accessing kdata[@"msg"], even though I'm sure from the debug that the object was initialised properly with a dictionary contains key "msg". When I debug the object, on the watch window, it shows me that the kdata data type keeps changing, from NSArrayM, NSSet, NSDictionary, etc. And its contents also keep changing. I even add retain keyword when calling completion ([responseObj retain]); but still produce error.

But if the code in class X is changed into like this:

// inside a networking class X implementation
- (void) doSomething:(completionBlock)completion {
    NSDictionary * json = // get from networking function, which will always have key "msg".
    Response * responseObj = [[Response alloc] initWithJson:json];
    if (completion != nil) { completion (responseObj); } // here is the change, no more switching to main thread
}

// inside caller method - no change here
[X doSomething:^(Response * response) {
    NSLog (@"%@", [response msg]);
}

The code works perfectly. Why is that happened? This is built in Xcode without ARC.

EDIT: someone mentioned about the init. This is my mistake that what was written above is not exactly my code, and I copy the init method wrong. This is my init method:

- (instancetype) initWithData:(NSDictionary *)freshData {
    NSParameterAssert(freshData); // make sure not nil
    self = [super init];
    if (self) {
        kdata = freshData;
    }
    return self;
}

2 Answers 2

1

The problem is the object get's released right when you call the 'async' . The way you declared your object is added to the autorelease pool since the control does not wait for 'async' to complete and the control return's by reaching the end of function 'doSomething' and releasing it's local objects which were added to the autorelease pool, and after that the memory location is used for other data and that's what you see confusing data. I think by adding the __block specifier in front of your declaration you instruct the code to capture this object in following blocks strongly and release it when the block finished executing. Give it a try.

// inside a networking class X implementation
    - (void) doSomething:(completionBlock)completion {
        NSDictionary * json = // get from networking function, which will always have key "msg".
        __block Response * responseObj = [[Response alloc] initWithJson:json];
        dispatch_async(dispatch_get_main_queue(), ^{
          if (completion != nil) { completion (responseObj); }
        });
    }
4
  • Yes, I was suspecting of the object was already released at the time my async call gets called, but I don't know how to remedy that situation. Ah I see! I never knew about this __block command. Is this command also happen to increase the counter as it's "copied" for use in the block, so it's not released at the end of the outer function? Commented Jan 20, 2017 at 4:08
  • yes, it increments retain count and it decreases it at the end of execution of the block, by then if the retain count is zero it'll be released in the next garbage collector cycle among with other auto releasable memory. But you mentioned you've already tried using 'retain' manually and it didn't work which makes me suspicious about it, so that's why I asked to try it.
    – Rhm Akbari
    Commented Jan 20, 2017 at 8:15
  • After understanding your explanation, I understand of course my retain method doesn't work, because I use the retain inside the block thread to pass the object to the completion block lol. By then, the object probably has already been released even before the retain method is called, so I was retaining a released memory block. xD Btw, thanks, this works! Commented Jan 20, 2017 at 10:03
  • That's great I'm happy. :)
    – Rhm Akbari
    Commented Jan 20, 2017 at 10:15
1
- (id)initWithJson:(NSDictionary *)data { kdata = data; }

You need call supers init here and return self. Start to learn basics.

1
  • You have a point. However, in my original code, the init function is already correct. I just incorrectly copy it to the question. So I have edited it to reflect the correct state. Commented Jan 19, 2017 at 6:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.