我有一個數據對象,我希望在iOS應用程序的所有不同視圖之間隨意存儲,訪問和修改數據對象。下面說明基本的設計前提。對我來說有趣的是,如果我用NSString替換NSMutableArray,這一切都行得通,沒什麼大不了的,但是當我將它製作成一個數組並存儲一個字符串時,它就嚇倒了。我選擇了一個數組,因爲我需要同時存儲不同版本的userData,並且在實際的應用程序中,不僅僅有一個用戶數據變量。爲什麼我在函數prepareForSegue中丟失了NSMutableArray中的對象?崩潰
我正在使用ARC,但我不得不承認如果我正確使用它,我不清楚。建議感激。
// data.h
@interface Data : NSObject
@property (nonatomic, retain) NSMutableArray *data;
@property (assign) NSNumber *Num; // determines which "level" on the array we're accessing
+(id) sharedInstance;
@end
// data.m
+(id) sharedInstance
{
static id sharedInstance = nil;
if (sharedInstance == nil) {
sharedInstance = [[self alloc] init];
}
return sharedInstance;
}
- (id)init
{
self = [super init];
if (self)
{
_Num = [NSNumber numberWithInt:0];
_data = [NSMutableArray array];
}
return self;
}
// userInput.h
@property (strong, nonatomic) IBOutlet UITextField *userData;
@property (nonatomic, retain) Data *dataStore;
在這裏,我一個空字符串添加到我的數據對象,因爲沒有用戶輸入的是強制性的,但如果沒有輸入我需要知道這一點,所以至少我用一個空字符串。
// userInput.m
viewDidLoad
{
_dataStore = [Data sharedInstance];
[_dataStore.data addObject:@""];
}
prepareForSegue
{
int num = [_dataStore.Num intValue];
NSString *transferData = [NSString stringWithFormat:@"%@", _userData.text];
[_dataStore.data replaceObjectAtIndex:num withObject:transferData]; // crash at this line. replacing the empty string with whatever the user inputs
}
崩潰報告
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM replaceObjectAtIndex:withObject:]: index 0 beyond bounds for empty array'
你爲什麼要重新創造'NSArray'? –
這與您的其他問題有關嗎?我在那裏查看了代碼,並且在嘗試調用replaceObjectAtIndex:withObject:之前,您正在調用數組上的removeAllObjects。你在這裏做同樣的事情嗎? – rdelmar
我同意rdelmar,這個問題在別處。然而,在回答關於ARC最佳實踐的問題時,我建議使用'strong'而不是'retain'和'weak'而不是'assign'。另外,你爲什麼要'Num'是'assign' /'weak'?如果你想讓你的'Data'對象保留它,你可能希望它是'強'。 – Rob