将对象添加到NSMutableArray时遇到问题 [英] Having problems with adding objects to NSMutableArray
问题描述
我在将对象添加到NSMutableArray * array时遇到问题.
I am having problem with adding objects to 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]);
结果:answerArray(1):(空)
Results: answerArray(1): (null)
推荐答案
首先,您要保留数组过多.
First off, you're over-retaining the array.
第二,您没有提供用于初始化数组的代码,因此我想它没有分配和初始化.这将导致代码向nil对象发送消息,并因此返回nil.
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.
您应该为Controller
对象创建init
方法,并分配一个新的NSMutableArray
对象(并保留它).
You should create an init
method for the Controller
object, and allocate a new NSMutableArray
object (and retain it).
还可以使用适当的dealloc
来释放阵列.
Also, a proper dealloc
to release the array.
这篇关于将对象添加到NSMutableArray时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!