NSMutableArray作为实例变量alway null

And*_*ndy 3 objective-c nsmutablearray ios

经过几个小时的浪费,我正式向专家寻求帮助!

我的问题在于使用NSMutableArray作为实例变量,并尝试添加对象并在我的类中的方法中返回数组.我显然做了一些根本错误的事情并且会感激帮助...我已经尝试了关于stackoverflow的其他类似问题的所有建议,阅读apple文档,以及我能想到的基本上所有试错编码的组合.可变数组总是返回(null).我甚至尝试为它们创建属性,但仍然数组返回(null)然后我也遇到内存管理问题,因为设置属性时保留,以及类的init方法中的init.

这是我想要做的:

1)循环通过一系列UISwitch,如果它们"打开",则在NSMutableArray中添加一个字符串

2)在另一个方法中将此可变数组分配给另一个数组

任何帮助非常感谢,

安迪

对于一些代码......

fruitsViewController.h

#import <UIKit/UIKit.h>

@interface fruitsViewController : UIViewController
{
    NSMutableArray *fruitsArr;
    UISwitch *appleSwitch;
    UISwitch *orangeSwitch;
}

@property (nonatomic,retain) NSMutableArray *fruitsArr; // ADDED ON EDIT
@property (nonatomic,retain) IBOutlet UISwitch *appleSwitch;
@property (nonatomic,retain) IBOutlet UISwitch *orangeSwitch;

- (IBAction)submitButtonPressed:(id)sender;
@end
Run Code Online (Sandbox Code Playgroud)

fruitsViewController.m

#import "fruitsViewController.h"

@implementation fruitsViewController

@synthesize fruitsArr; // ADDED ON EDIT
@synthesize appleSwitch, orangeSwitch;

/* COMMENTED OUT ON EDIT
-(id)init
{
    if (self = [super init]) {
        // Allocate memory and initialize the fruits mutable array
        fruitsArr = [[NSMutableArray alloc] init];
    }
    return self;
}
*/

// VIEW DID LOAD ADDED ON EDIT
- (void)viewDidLoad
{
    self.fruitsArr = [[NSMutableArray alloc] init];
}

- (void)viewDidUnload
{
    self.fruitsArr = nil;
    self.appleSwitch = nil;
    self.orangeSwitch = nil;
}

- (void)dealloc
{
    [fruitsArr release];
    [appleSwitch release];
    [orangeSwitch release];
    [super dealloc];
}

- (IBAction)submitButtonPressed:(id)sender
{
    if ([self.appleSwitch isOn]) {
        [self.fruitsArr addObject:@"Apple"; // 'self.' ADDED ON EDIT
    }
    if ([self.orangeSwitch isOn]) {
        [self.fruitsArr addObject:@"Orange"; // 'self.' ADDED ON EDIT
    }
    NSLog(@"%@",self.fruitsArr); // Why is this returning (null) even if the switches are on?!
    [fruitsArr addObject:@"Hello World";
    NSLog(@"%@",self.fruitsArr); // Even trying to add an object outside the if statement returns (null)
}
@end
Run Code Online (Sandbox Code Playgroud)

Sim*_*ain 7

似乎你的init函数永远不会被调用.如果要从NIB初始化此视图控制器,则需要使用initWithCoder.如果没有,只需在viewDidLoad中声明您的fruitsArr.