自定义类的对象没有获取存储在NSMutableArray

问题描述:

我想将对象添加到NSMutableArray但编写以下代码后,我得到benchmarkArray NIL。哪里出错帮我请自定义类的对象没有获取存储在NSMutableArray

[benchmark setBenchmarkTitle:self.benchmarkTitle.text]; 
    [benchmark setBenchmarkDescription:self.benchmarkDescription.text]; 
    [benchmarkArray addObject:benchmark]; 

我的Benchmark类是:

@interface Benchmark : NSObject 

@property (nonatomic, retain) NSString *bid; 
@property (nonatomic, retain) NSString *benchmarkTitle; 
@property (nonatomic, retain) NSString *benchmarkDescription; 

-(id)initWithCoder: (NSCoder *)coder; 
-(void)encodeWithCoder:(NSCoder *)encoder; 

@end 

@implementation Benchmark 

@synthesize bid; 
@synthesize benchmarkTitle; 
@synthesize benchmarkDescription; 

- (id) initWithCoder:(NSCoder *)coder { 

    self = [super init]; 
    if(self) { 
     bid = [coder decodeObjectForKey:@"id"]; 
     benchmarkTitle = [coder decodeObjectForKey:@"benchmarkTitle"]; 
     benchmarkDescription = [coder decodeObjectForKey:@"benchmarkDescription"]; 
    } 
    return self; 
} 

- (void) encodeWithCoder:(NSCoder *)encoder { 

    [encoder encodeObject:bid forKey:@"id"]; 
    [encoder encodeObject:benchmarkTitle forKey:@"benchmarkTitle"]; 
    [encoder encodeObject:benchmarkDescription forKey:@"benchmarkDescription"]; 
} 

@end 
+0

是否使用ARC? – 2013-03-08 10:31:22

+0

您确定编码器已正确初始化吗? – TeaPow 2013-03-08 10:32:42

+0

他说benchmarkarray是零,不是空的 – peko 2013-03-08 10:33:49

你忘了分配和初始化

benchmarkArray = [[NSMutableArray alloc] init]; 
+0

哦,是的,我忘了初始化阵列感谢pekoe – 2013-03-08 10:58:51

没有错,你的Benchmark类。

您的问题在于您创建的课程benchMarkArray

使得它的属性后,您需要初始化它init/awakeFromNib/viewDidLoad方法:

benchMarkArray=[[NSArray alloc]init]; 

,或者

benchmarkArray=[NSArray new]; 
+0

- (void)viewDidLoad { [super viewDidLoad]; //设置类别/基准类对象 self.category = [[Category alloc] init]; self.benchmark = [[Benchmark alloc] init]; } 我已经初始化它 – 2013-03-08 10:37:13