-1

我正在尝试制作一个 TableViewController .. 我使用 youtube 课程中的代码让它工作:“Cocoa Programming L13-14” 但是当我尝试更改它以便默认值不是硬编码时......但是而不是 Interface Builder 中控件的值,我得到 (null) 全面。这是代码:

#import <Foundation/Foundation.h>

@interface Person : NSObject {
    IBOutlet NSPathControl* pcSource;
    IBOutlet NSPathControl* pcDestination;
    IBOutlet NSTextField* tfBackupAmount;

    NSURL* urlSource;
    NSURL* urlDestination;
    NSString* strBackupAmount;

    //Old--
    //NSString* name;
    //int age;
}

@property NSURL* urlSource;
@property NSURL* urlDestination;
@property NSString* strBackupAmount;

//Old--
//@property (copy) NSString* name;
//@property int age;

@end

#import "Person.h"

@implementation Person

@synthesize urlSource;
@synthesize urlDestination;
@synthesize strBackupAmount;

//Old--
//@synthesize name;
//@synthesize age;

- (id)init {
    self = [super init];
    if (self) {
        urlSource = [pcSource URL];
        urlDestination = [pcDestination URL];
        strBackupAmount = [tfBackupAmount stringValue];
        NSLog(@"%@\n%@\n%@",urlSource,urlDestination,strBackupAmount);

        //Old--
        //name = @"Yoda";
        //age = 900;
        //NSLog(@"%@: %i", name, age);
    }
    return self;
}
@end

一切都评论了 //Old-- 工作正常,并且与 TableViewController 交互良好。所以我假设所有这些仍然可以正常工作。3 个控件(2 个 NSPathControl 和 1 个 NSTextField)被链接到一个 Object 类:Interface Builder 中的 Person,这些控件被链接起来。为什么我得到以下输出:

(null)
(null)
(null)

? 当我到达 NSLog(); 线?我哪里错了?谢谢!

4

3 回答 3

1

pcSource, pcDestination, 或在调用tfBackupAmount您的方法时未初始化init,因此它们都是nil. 在 Objective-C 中向 to 发送消息nil是合法的,并且您会立即nil返回。这意味着urlSource,urlDestinationstrBackupAmount都是nil,这就是为什么你会看到你看到的日志输出。

您需要将日志消息更改为初始化这些变量后的某个时间。

于 2013-09-18T20:18:30.947 回答
0

好的,从技术上讲,这个问题 - 我找到了答案。就是做一个自定义的init方法。就我而言,这意味着:

Person* p = [[Person alloc] initWithurlSource:[NSURL URLWithString:@"moo"] andurlDestination:[NSURL URLWithString:@"cow"] andstrBackupAmount:@"foo"];

但是,这仍然不能解决我从已公开为@property 的另一个类(在本例中为我的 TableViewController 类)获取 IBOutlets 值的问题:

@interface AppDelegate : NSObject <NSApplicationDelegate> {
.....
.....
@property (nonatomic, retain) NSPathControl* pcSource;
@property (nonatomic, retain) NSPathControl* pcDestination;
@property (nonatomic, retain) NSTextField* tfBackupAmount;

我仍然无法在我的“addButtonPressed”方法中获取这些控件的值:

//ad is AppDelegate - declared in interface as AppDelegate* ad;
NSPathControl* pcSource = [ad pcSource];
NSPathControl* pcDestination = [ad pcDestination];
NSTextField* tfBackupAmount = [ad tfBackupAmount];
于 2013-09-19T02:22:11.243 回答
0

尝试将代码放入 -viewDidLoad 而不是 -init。这一切都与事件的顺序有关(-init 在任何 IB 事情发生之前被调用。

于 2013-09-18T20:18:41.350 回答