开发者

Having problems with adding objects to NSMutableArray

开发者 https://www.devze.com 2023-02-05 17:06 出处:网络
I am having problem with adding objects to NSMutableArray *array. //Controller.m #import \"Controller.h\"

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]);

Results: an开发者_运维技巧swerArray(1): (null)


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.

You should create an init method for the Controller object, and allocate a new NSMutableArray object (and retain it).

Also, a proper dealloc to release the array.


NSMutabaleArray starts at index 0


Here is the method I added to Controller class:

- (id)init {
    self = [super init];
    if(self){
        array = [[NSMutableArray alloc] init];
    }
    return self;
}
- (void)dealloc {
    [array release];
    [super dealloc];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号