浪費了很多時間之後,我正式向專家求助!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