【发布时间】:2017-01-16 10:14:23
【问题描述】:
我有一个这样的对象:
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]);
}
此代码在访问kdata[@"msg"] 时会引发错误,即使我从调试中确定该对象已使用包含键"msg" 的字典正确初始化。当我调试对象时,在监视窗口上,它显示 kdata 数据类型不断变化,从NSArrayM、NSSet、NSDictionary 等。它的内容也在不断变化。我什至在调用completion ([responseObj retain]); 时添加了retain 关键字,但仍然产生错误。
但是如果把X类中的代码改成这样:
// 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]);
}
代码完美运行。为什么会这样?这是在没有 ARC 的 Xcode 中构建的。
编辑:有人提到了 init。这是我的错误,上面写的不完全是我的代码,我把init方法复制错了。这是我的初始化方法:
- (instancetype) initWithData:(NSDictionary *)freshData {
NSParameterAssert(freshData); // make sure not nil
self = [super init];
if (self) {
kdata = freshData;
}
return self;
}
【问题讨论】:
标签: ios objective-c xcode automatic-ref-counting