PrefMySpotsViewCtrl.h
@class Location;
@interface PrefMySpotsViewCtrl : NSViewController
{
NSTextField *locationSearchInput;
NSString * enteredLocation;
Location *l;
}
@property (nonatomic, retain) IBOutlet NSTextField *locationSearchInput;
@property (nonatomic, retain) NSString *enteredLocation;
PrefMySpotsViewCtrl.m
#import "Location.h"
- (void) controlTextDidChange:(NSNotification *)aNotification
{
enteredLocation = [locationSearchInput stringValue];
NSLog(@"in class:%@", enteredLocation);
[l searchLocation];
}
Location.h
@class PrefMySpotsViewCtrl;
@interface Location : NSObject
{
PrefMySpotsViewCtrl *p;
}
- (void) searchLocation;
Location.m
#import "Location.h"
#import "PrefMySpotsViewCtrl.h"
@implementation Location
- (void) searchLocation
{
NSLog(@"out of class: %@", [p enteredLocation]);
}
用户输入a到locationSearchInput
,这是输出
2012-09-30 10:18:12.915 MyApp[839:303] in class:
2012-09-30 10:18:12.917 MyApp[839:303] in class:a
永远不会执行 searchLocation
方法。
如果我执行l = [[Location alloc] init];
,则会执行searchLocation
,但输出为null
2012-09-30 10:28:46.928 MyApp[880:303] in class:
2012-09-30 10:28:46.929 MyApp[880:303] out of class: (null)
2012-09-30 10:28:46.930 MyApp[880:303] in class:a
2012-09-30 10:28:46.931 MyApp[880:303] out of class: (null)
有什么想法吗?
感谢?
答案 0 :(得分:2)
但问题是:您是否已将有效的控制器实例(PrefMySpotsViewCtrl)分配给位置对象?
我的意思是:
l = [[Location alloc] init];
l->p = self;
[l searchLocation];
请记住,最好将PrefMySpotsViewCtrl声明为Location声明中的属性,如下所示:
@interface Location : NSObject
{
PrefMySpotsViewCtrl *p;
}
@property (nonatomic, assign) PrefMySpotsViewCtrl *p;
然后使用属性setter分配它:
l = [[Location alloc] init];
l.p = self;
[l searchLocation];
修改强>
由于下面的评论似乎OP不理解逻辑,我发布一个简单的例子让他更好地理解:
1)ClassA声明:
@interface ClassA : NSObject
@property(nonatomic,retain) NSString *ABC;
@end
2)ClassB声明:
@interface ClassB : NSObject
@property(nonatomic,assign) ClassA *p;
-(void) printClassAvar;
@end
@implementation ClassB
-(void) printClassAvar {
NSLog(@"Variable = %@", [self.p ABC]);
}
@end
3)用法:
ClassA *a = [ClassA new];
a.ABC = @"XZY";
ClassB *b = [ClassB new];
b.p = a;
[b printClassAvar];
答案 1 :(得分:1)
您尚未展示您的初始化方法。
您可能实际上没有为l
创建iVar。就像这样:
// in the view controllers `initWithNibName:bundle:` method
l = [Location alloc] init]; // or whatever the inititializer for a Location object is.
因为你还没有创建l
类型的对象,所以它是nil
(无论如何都使用较新的LLVM编译器),并且它不会接收消息,所以永远不会调用你的方法。 / p>