-2

好的,所以我试图让用户从 iphone 照片中选择图像并将该图像保存为按钮上的图像。当用户关闭应用程序并再次打开它时,我希望用户再次看到他保存的图像:) theButton 包含单击哪个按钮的发送者。

我可以做用户可以将图像作为按钮图像的部分。我用这条线来设置图像

[theButton setImage:btnImage forState:UIControlStateNormal];

现在我想知道如何访问该按钮的图像?所以我可以保存和加载它吗?

我根据教程使用此代码,但我被加载部分卡住了,因为显然我不必使用 Imageview,因为它只是可读的:) 我的代码:

//SAVE
-(NSString *)pathOfFile{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsFolder = [paths objectAtIndex:0];
    return [documentsFolder stringByAppendingFormat:@"myfile.plist"];
}

-(void)applicationWillTerminate:(NSNotification*)notification{
    NSMutableArray *array = [[NSMutableArray alloc]init];
    [array addObject: tileOne.imageView];
    [array addObject: tileTwo.imageView];
    [array writeToFile:[self pathOfFile] atomically:YES];
}

//LOAD
- (void)viewDidLoad
{
    NSString *filePath = [self pathOfFile];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath];
        //Here it says read only, what to use then?
        tileOne.imageView = [array objectAtIndex:0];

    }

    UIApplication *app = [UIApplication sharedApplication];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app];

    [super viewDidLoad];

}
4

2 回答 2

1

tileOne 是一个什么样的对象?如果它是 UIButton,您回答了自己的问题,只需执行以下操作:

[tileOne setImage:[array objectAtIndex:0] forState:UIControlStateNormal];
于 2013-05-10T18:54:36.193 回答
0

您还可以查看NSCoding。鉴于UIImage *image;您的头文件中有一个或某些内容,我想您可以使用类似

-(void)saveImage
{
    NSString *filePath =[documentsFolder stringByAppendingPathComponent:@"file.x";
    NSMutableData *dataToSave = [NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:dataToSave];
    [archiver encodeObject:image forKey:@"theImage"]; //if 'image' is I.E an UIImage
    [archiver finishEncoding];
    [dataToSave writeToFile filePath options:NSDataWritingAtomic error:&error];//do some additional error-stuff
}
-(void)openImage
{
    NSString *filePath =[documentsFolder stringByAppendingPathComponent:@"file.x";
    if([[NSFileManager defaultManager] fileExistsAtPath])
    {
        NSData *data = [[NSData alloc]initWithContentsOfFile:filePath];
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initWithReadingWithData:data];
        image = [unarchiver decodeObjectForKey:@"theImage"];
        [unarchiver finishDecoding];
    }
    else
    {
        //No images was previously saved, do something else, image = nil
    }
}
于 2013-05-11T14:13:15.713 回答