【发布时间】:2013-08-13 05:23:48
【问题描述】:
有红色、蓝色和黄色 3 个等级。每当按下按钮时,黄色类通知蓝色类并通过委托传回一个字符串。这一点工作正常。好吧,现在蓝色类正在尝试在委托实现方法中调用红色类实例方法 displayString。但是由于某种原因,这个实例方法永远不会被调用。经过调试,我发现 [self.red displayString:col]; 中的 self.red 为空。但是我在 Blue 类的另一个类实例方法中使用 self.red ,然后 self.red 不是 NULL 。是不是少了什么东西
@interface RedClass : NSObject
-(void)displayString:(NSString*)str;
@end
@implementation RedClass
-(void)displayString:(NSString*)str
{
NSLog(@"The string:%@",str);
}
@end
// BlueClass.h
@interface BlueClass:UIViewController<YellowDelegate>
@property (nonatomic, strong) RedClass *red;
@end
//实现delegateExample并调用example类的类实例方法的类
// BlueClass.m
@implementation BlueClass
- (void)colorChanged:(NSString*)col
{
[self.red displayString:col];
}
@end
//YellowClass
@protocol YellowDelegate<NSObject>
-(void)colorChanged:(NSString *)col;
@end
@interface YellowClass:UIView
@property (nonatomic, weak) id <YellowDelegate> delegate;
@end
//黄色类.m @implementation YellowClass
(IBAction)btnPressed:(id)btn
{
[self.delegate colorChanged:@"yellow"];
}
@end
【问题讨论】:
-
在 BlueClass 中的何处以及如何创建 RedClass 的实例?
-
这与您几个小时前的问题有何不同?这似乎是它的抽象stackoverflow.com/questions/18170130/…
-
是的,它是一样的。我想知道从委托实现中调用类实例方法是否有任何限制。是的,我在 viewDidload() 中创建了 RedClass 的实例。我只是跳过了那个..这就是 self.red 在其他类实例方法中不为空的全部解释,并且它在委托实现中以某种方式为空。那么为什么 self.red 在其他实例方法中工作得很好,却在委托实现方法中变为 null
-
如果不知道何时何地调用这些其他正常工作的类实例方法,很难回答这个问题。为什么会这样:“@property (nonatomic, strong) example *red”,而不是:“@property (nonatomic, strong) RedClass *red”?什么是“例子”?
-
到底什么是“类实例方法”?有类方法,也有实例方法。但是类实例方法?从来没有听说过他们。
标签: objective-c methods delegates