从另一个类访问NSMutableArray

时间:2013-02-22 08:42:23

标签: objective-c xcode nsmutablearray

这就是我的实体类的外观:

BaseDataEntity.h

#import -Foundation/Foundation.h

@interface BaseDataEntity : NSObject

@property (assign) NSMutableArray *cbxDataList;
@property (assign) NSString  *resaultText;

@end

BaseDataEntity.m

#import "BaseDataEntity.h"

@implementation BaseDataEntity

@synthesize cbxDataList = _cbxDataList;
@synthesize resaultText = _resaultText;

@end

这就是我尝试访问它们的方式:

-(void)applicationDidFinishLaunching:(NSNotification *)aNotification{

    BaseDataEntity *aBaseDataEntity = [[BaseDataEntity alloc] init];
    [self setBaseDataEntity:aBaseDataEntity];

}

-(IBAction)ReadPort:(id)sender {

    NSMutableArray* array = [[NSMutableArray alloc] init];
    for (int i=0; i<10; i++) {
        NSString *temp = [NSString stringWithFormat:@"Test %d", i];
        [array addObject:temp];
    }
    [self.baseDataEntity setCbxDataList:array];

    NSLog(@" cbxDataList count = %lu",[array count]);
    [array release];

    [self.baseDataEntity setResaultText:@"Test"];
    [self updateUserInterface:TRUE];
}


-(void)updateUserInterface:(BOOL)piClear{

    NSString *textValue = [NSString stringWithFormat:@"%@"
                           ,[self.baseDataEntity resaultText]];

    if([self.ResaultTextField stringValue] != nil && !piClear){
        textValue = [NSString stringWithFormat:@"%@\n%@", textValue
                     ,[self.ResaultTextField stringValue]];
    }

    NSMutableArray* array = [[NSMutableArray alloc] initWithArray:
        [self.baseDataEntity.cbxDataList value]];

    for (int i = 0; i < [array count]; i++) {
        textValue = [NSString stringWithFormat:@"%@\n%@", textValue
                     ,[array objectAtIndex:i]];
    }
    [array release];

    [self.ResaultTextField setStringValue:textValue];
}

问题是我可以更新resaultText并可以访问此值。但cbxDataList值始终为空。

3 个答案:

答案 0 :(得分:0)

您应该使用retain而不是assign来增加cbxDataList的保留计数。

@property (retain) NSMutableArray   *cbxDataList;

请注意,该对象需要在某个时候释放,否则您可能会发生内存泄漏。

答案 1 :(得分:0)

在下面的功能中,

-(void)updateUserInterface:(BOOL)piClear

数组创建错误。

NSMutableArray* array = [[NSMutableArray alloc] initWithArray:
        [self.baseDataEntity.cbxDataList value]];

以上代码无需替换,

NSMutableArray* array = [[NSMutableArray alloc] initWithArray:
        self.baseDataEntity.cbxDataList];

答案 2 :(得分:0)

试试这些:

@property (retain) NSMutableArray *cbxDataList; 
@property (assign) NSString  *resaultText;

并在-(void)applicationDidFinishLaunching:(NSNotification *)aNotification

分配+ init这两个。