浪费了很多时间之后,我正式向专家求助!NSMutableArray作为实例变量总是空的
我的问题在于使用NSMutableArray作为实例变量,并尝试添加对象并在我的类的方法中返回数组。我明显在做一些根本性错误的事情,并会很感激的帮助......我已经尝试了其他类似的关于stackoverflow的问题的所有建议,阅读苹果文档,以及基本上所有我可以想到的尝试和错误编码的组合。可变数组一直返回(null)。我甚至尝试为它们创建属性,但数组仍然返回(空),然后由于在设置属性时保留了内存管理问题,并且在类的init方法中还初始化了init。
这里就是我想要做:
1)循环通过一系列UISwitches的,如果他们“接通”,一个字符串添加到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
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
尝试写alloc和阵列中运行init在viewDidLoad中 – 2012-02-03 10:27:30