从NSArrayController设置模型类中的Array

时间:2013-01-31 22:46:40

标签: macos cocoa nsarraycontroller

如何在我的AppDelegate类中使用ValueItem的内容在我的模型类NSArrayController中设置数组:

@interface AppDelegate : NSObject <NSApplicationDelegate>
{
    ValueItem *vi;
}

@implementation AppDelegate
{

    ValueItem *array = [[ValueItem alloc]init];
    [array setValueArray:[outArrayController arrangedObjects]];

    NSArray *testArray2 = vi.valueArray; // !!!getter or setter doesn't work!!!
    NSLog(@"test array 2 is:%@", testArray2);
}

NSLog返回NULL。我在这里想念什么? (valueArray初始化为@property@synthesize

ValueItem.h:

#import <Foundation/Foundation.h>
@interface ValueItem : NSObject
{
    NSNumber *nomValue;
    NSNumber *tolerancePlus;
    NSNumber *toleranceMinus;
    NSMutableArray *valueArray;
}
@property (readwrite, copy) NSNumber *nomValue;
@property (readwrite, copy) NSNumber *tolerancePlus;
@property (readwrite, copy) NSNumber *toleranceMinus;
@property (nonatomic, retain) NSMutableArray *valueArray;

@end

ValueItem.m:

#import "ValueItem.h"
@implementation ValueItem

@synthesize nomValue, tolerancePlus, toleranceMinus;
@synthesize valueArray;

-(NSString*)description
{
    return [NSString stringWithFormat:@"nomValue is: %@ | tolerancePlus is: %@ | toleranceMinus is: %@", nomValue, tolerancePlus, toleranceMinus];

}
@end

1 个答案:

答案 0 :(得分:0)

解决方案:需要确保您正在处理AppDelegate的vi媒体资源:

// We need to make sure we're manipulating the AppDelegate's vi property!
self.vi = [[ValueItem alloc]init];
[vi setValueArray:[outArrayController arrangedObjects]];

NSArray *testArray2 = vi.valueArray; // !!!getter or setter doesn't work!!!
NSLog(@"test array 2 is:%@", testArray2);

解释: 在前两行中,您操纵array ValueItem变量,然后尝试将testArray2设置为未初始化的vi ValueItem变量的值。

// This is a new variable, unrelated to AppDelegate.vi
ValueItem *array = [[ValueItem alloc]init];
[array setValueArray:[outArrayController arrangedObjects]];

// Here, AppDelegate.vi hasn't been initialized, so valueArray *will* be null!
NSArray *testArray2 = vi.valueArray; 
NSLog(@"test array 2 is:%@", testArray2);