-1

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];
}

位置.h

@class PrefMySpotsViewCtrl;

@interface Location : NSObject

{
  PrefMySpotsViewCtrl *p;  
}

- (void) searchLocation;

位置.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)

任何的想法?

谢谢?

4

2 回答 2

2

但是,问题是:您是否为位置对象分配了一个有效的控制器实例(PrefMySpotsViewCtrl)?

我是说 :

l = [[Location alloc] init];
l->p = self;
[l searchLocation];

请记住,最好将 PrefMySpotsViewCtrl 声明为 Location 声明中的属性,如下所示:

@interface Location : NSObject
{
  PrefMySpotsViewCtrl *p;  
}
@property (nonatomic, assign) PrefMySpotsViewCtrl *p;

然后使用属性设置器分配它:

l = [[Location alloc] init];
l.p = self;
[l searchLocation];

编辑

由于从下面的评论看来 OP 不理解逻辑,我发布了一个简单的例子让他更好地理解:

1)A类声明:

@interface ClassA : NSObject
@property(nonatomic,retain) NSString *ABC;
@end

2)B类声明:

@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];
于 2012-09-30T08:42:39.933 回答
1

You haven't shown your init method.

It is possible that you haven't actually created an iVar for l. i.e something like:

// in the view controllers `initWithNibName:bundle:` method
l = [Location alloc] init]; // or whatever the inititializer for a Location object is.

Because you haven't created an object of type l it is nil (with the newer LLVM compiler anyway), and it doesn't receeive messages, so your method is never called.

于 2012-09-30T08:42:56.580 回答