我正在用故事板構建一個應用程序。我有一個視圖控制器,用戶有一組工具(UILabels,圖像...),並且可以通過單擊特定按鈕來添加這些項目。當我退出視圖控制器或關閉應用程序,雖然所有的數據都丟失了。所以我想以這種方式建立一個保存按鈕:用NSMutableData和NSKeyedArchiver保存一個UIO對象
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *cameraButton = [[UIBarButtonItem alloc]
initWithTitle:@"Camera"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(useCamera:)];
UIBarButtonItem *cameraRollButton = [[UIBarButtonItem alloc]
initWithTitle:@"Camera Roll"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(useCameraRoll:)];
NSArray *items = [NSArray arrayWithObjects: cameraButton,
cameraRollButton, nil];
[toolbar setItems:items animated:NO];
mouseMoved = 0;
array = [[NSMutableArray alloc]init];
array2 = [[NSMutableArray alloc]init];
array3 = [[NSMutableArray alloc]init];
NSFileManager *filemgr; NSString *docsDir; NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the data file
dataFilePath = [[NSString alloc] initWithString: [docsDir
stringByAppendingPathComponent: @"data.archive"]];
// Check if the file already exists
if ([filemgr fileExistsAtPath: dataFilePath]) {
dataArray = [NSKeyedUnarchiver unarchiveObjectWithFile: dataFilePath];
array = [dataArray objectAtIndex:0]; array2 = [dataArray objectAtIndex:1]; array3 = [dataArray objectAtIndex:2];
}}
-(void)saveData{
NSMutableArray *contactArray;
contactArray = [[NSMutableArray alloc] init]; [contactArray addObjectsFromArray:array]; [contactArray addObjectsFromArray:array2]; [contactArray addObjectsFromArray:array3]; [NSKeyedArchiver archiveRootObject:
contactArray toFile:dataFilePath];
[self.view addSubview: image1];
[self.view addSubview: text1];
[self.view addSubview: label1];
}
當我按下按鈕,你可以看到,代碼是觸發(NSLog的),但沒有任何反應。在上面的例子中,當我點擊保存時,用戶創建(分配)的UILabel應該被保存,並且當應用程序再次打開時,按鈕取消歸檔應該將標籤完全放在原來的位置,並放在相同的位置。即使是UIImageViews和UITextFields,我也必須做。
因爲我在數組中添加了所有用戶創建的標籤...我想將整個對象保存在數組中。上面的代碼雖然不起作用。我無法理解why.this是我如何創建數組和對象(在.H我加的NSMutableArray *陣列;)
CGRect labelFrame = CGRectMake(400, 100, 100, 30);
label1 = [[UILabel alloc] initWithFrame: labelFrame];
[label1 setText: @"Untitled"];
[label1 setTextColor: [UIColor orangeColor]];
[self.view addSubview:label1];
label1.backgroundColor = [UIColor clearColor];
UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scalePiece:)];
[label1 addGestureRecognizer:pinchGesture];
if (array == nil) array = [[NSMutableArray alloc]init];
[array addObject:label1];
在此先感謝您的幫助!
現在它的工作原理,但只適用於最後創建的對象,但我希望所有的對象都是數組。我試圖查找MVC,但它只有一個模型。這是一種更有效的方式嗎?你能保存孔視圖控制器嗎? – Alessandro 2012-04-02 17:53:45