将委托作为 id 发送而不是将其设置为属性?
我有一个类对象,我在不同的地方经常使用它。
现在我正在使用这样的类:
myClass.delegate = self;
[myClass doSomething];
doSomething 创建一个新的类对象来计算内容,并且可能需要长达 1 分钟的时间才能将结果发送回委托,如下所示:
-(void)doSomething {
CalculateStuff *calc = [[calculateStuff alloc] init];
calc.delegate = self;
[calc calculate];
}
/* Calculate Delegate */
-(void)didCalculate {
[[self delegate] didDoSomething];
}
问题是我从另一个地方调用相同的东西它会调用我最新的代表,这会导致很多问题。
问题:
有没有办法将委托作为对象发送,而不必将其设置为属性? 我是这样写的,Xcode 给我警告“MyClass 的不完整实现”
[myClass doSomethingWithDelegate:self];
并且
-(void)doSomethingWithDelegate:(id)delegate {
CalculateStuff *calc = [[calculateStuff alloc] init];
[calc calculateWithDelegate:delegate];
}
/* Calculate Delegate */
-(void)didCalculateWithDelegate:(id)delegate {
[delegate didDoSomething];
}
编辑 刚刚尝试了一下,似乎可以工作,但是我怎样才能摆脱 Xcode 中的警告呢?
I have a class object that i'm using a lot from different places.
Now i'm using the class like this:
myClass.delegate = self;
[myClass doSomething];
doSomething creates a new class object that calculate stuff and can take up to 1 min before it sends back a result to the delegate like this:
-(void)doSomething {
CalculateStuff *calc = [[calculateStuff alloc] init];
calc.delegate = self;
[calc calculate];
}
/* Calculate Delegate */
-(void)didCalculate {
[[self delegate] didDoSomething];
}
Problem is that i from another place is calling the same thing it will call my latest delegate and this causes a lot of problems.
Question:
Is there a way to send the delegate as an object without having to set it as the property?
I've written it like this and Xcode give me warnings "Incomplete implementation of MyClass"
[myClass doSomethingWithDelegate:self];
And
-(void)doSomethingWithDelegate:(id)delegate {
CalculateStuff *calc = [[calculateStuff alloc] init];
[calc calculateWithDelegate:delegate];
}
/* Calculate Delegate */
-(void)didCalculateWithDelegate:(id)delegate {
[delegate didDoSomething];
}
EDIT
Just tried it out and it seems to work, but how can i get rid of the warnings in Xcode?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您的问题是您忘记从类的接口(或类扩展)中删除
doSomething
和didCalculate
的声明。理想情况下,您应该创建一个协议来确保您的委托具有所需的方法。例如:
然后使用
id
而不仅仅是id
。传递一个块也是解决这个问题的有效方法,尽管它有点棘手。
I think your problem is that you forgot to remove the declaration of
doSomething
anddidCalculate
from your class's interface (or class extension).Ideally you should create a protocol to ensure that your delegate has the required method(s). For instance:
Then use
id<DoSomethingDelegate>
instead of justid
.Passing a block would also be a valid solution to this problem, although it's a bit trickier.