[英]Having problems with adding objects to NSMutableArray
I am having problem with adding objects to NSMutableArray *array. 我在将对象添加到NSMutableArray * array时遇到问题。
// Controller.m
#import "Controller.h"
@implementation Controller
- (void)parser:(NSString *)string{
[array addObject:string];
NSLog(@"answerArray(1): %@",[array objectAtIndex:1]);
[array retain];
}
@end
// Controller.h
#import <Foundation/Foundation.h>
@interface Controller : NSObject {
NSMutableArray *array;
}
- (void)parser:(NSString *)string;
@end
NSLog(@"answerArray(1): %@",[array objectAtIndex:1]); NSLog(@“ answerArray(1):%@”,[array objectAtIndex:1]);
Results: answerArray(1): (null) 结果:answerArray(1):(空)
NSMutabaleArray从索引0开始
First off, you're over-retaining the array. 首先,您要过度保留阵列。
Second, you didn't provide the code for initializing the array, so I guess it's not allocated and initialized. 其次,您没有提供用于初始化数组的代码,因此我想它没有分配和初始化。 This will cause the code to message a nil object and thus return nil.
这将导致代码向nil对象发送消息,并因此返回nil。
You should create an init
method for the Controller
object, and allocate a new NSMutableArray
object (and retain it). 您应该为
Controller
对象创建一个init
方法,并分配一个新的NSMutableArray
对象(并保留它)。
Also, a proper dealloc
to release the array. 此外,适当
dealloc
释放阵列。
Here is the method I added to Controller class: 这是我添加到Controller类的方法:
- (id)init {
self = [super init];
if(self){
array = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc {
[array release];
[super dealloc];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.