我正在用故事板构建一个应用程序。我有一个视图控制器,用户有一组工具(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