【问题标题】:Delegate method won't fire (is null). Using ARC委托方法不会触发(为空)。使用 ARC
【发布时间】:2011-10-21 16:18:41
【问题描述】:

我无法触发我的委托方法。我有以下代码:

@class Location;
@protocol LocationDelegate
- (void)location:(Location*)location foundLocation:(CLLocation*)location;
- (void)location:(Location*)location failedToLocateUserWithError:(NSError*)error;
@end 

@interface Location : NSObject {
    __unsafe_unretained id <LocationDelegate> delegate;
}

@property (nonatomic, assign) id <LocationDelegate> delegate;

@end

...
@implementation Location

@synthesize delegate;

- (void)startUpdatingLocation {
    NSLog(@"%@", delegate); // prints '(null)'
    ...

}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSLog(@"%@", delegate); // prints '(null)'
    [delegate location:self foundLocation:newLocation];
}

@end

以前在其他项目中工作得很好,所以想知道它是否与 ARC 有关?分配Location 的对象确实符合LocationDelegate。我还将代表设置为自我。但是委托方法没有触发,如果我输出它,它就是空的。

谢谢

【问题讨论】:

    标签: ios delegates automatic-ref-counting


    【解决方案1】:

    仅从您在此处粘贴的代码来看,我没有看到任何东西保留了您的委托(保留的引用)。

    您粘贴的所有内容都特别表明您正在竭尽全力不让此代码保留委托。

    如果这就是您想要的样子,那么您最好确保它已被保留在其他地方 - 否则 ARC 将正确得出结论,由于没有人对委托有强(保留)引用,因此它是安全(且适当)的释放它。

    分配Location的对象确实符合LocationDelegate。一世 我还将委托设置为 self。

    谁对那个对象有强烈的引用?

    【讨论】:

    • 我尝试将其更改为 (nonatomic, strong) 并且没有 unsafe_unretained,但仍然没有。
    • 摆脱 ivar。在您引用委托的行(例如:[delegate location....)上,请改用self.delegate
    • 赋值后,在调试器中添加一个watch,然后你会看到它何时变为nil。
    • 您说您在某个时候分配了委托属性。在该行上放置一个断点。跨过去。然后在调试器中添加一个watch。
    • 在我分配Location的类中,我设置location.delegate = self;
    【解决方案2】:

    无论您在哪里分配Location,您都分配了代理吗? 例如: Location *location = [[Location alloc] init]; location.delegate = self;

    【讨论】:

    • 他特别说他是:I am also setting the delegate to self.
    • 尝试在@protocol LocationDelegate 之后添加
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多