objective-c singleton shall store UIimage. Does not work
我有一个单件的地方,想在单件存储一个
如何在我的单例上存储一个
1 2 3 4 5 6 7 8 9 10 11 | #import <Foundation/Foundation.h> @interface SingletonClass : NSObject @property (strong, nonatomic) NSMutableArray *myArray; @property (strong, nonatomic) UIImage *photo; + (id)sharedInstance; -(void)setPhoto:(UIImage *)photo @end |
单身汉
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #import"SingletonClass.h" @implementation SingletonClass static SingletonClass *sharedInstance = nil; // Get the shared instance and create it if necessary. + (SingletonClass *)sharedInstance { if (sharedInstance == nil) { sharedInstance = [[super allocWithZone:NULL] init]; } return sharedInstance; } // We can still have a regular init method, that will get called the first time the Singleton is used. - (id)init { self = [super init]; if (self) { // Work your initialising magic here as you normally would self.myArray = [[NSMutableArray alloc] init]; self.photo = [[UIImage alloc] init]; } return self; } // We don't want to allocate a new instance, so return the current one. + (id)allocWithZone:(NSZone*)zone { return [self sharedInstance]; } // Equally, we don't want to generate multiple copies of the singleton. - (id)copyWithZone:(NSZone *)zone { return self; } -(void)setPhoto:(UIImage *)photo { photo = _photo; } |
详细视图
1 2 3 4 5 6 7 8 9 10 | -(void)sharePhoto:(id)sender { SingletonClass *sharedSingleton = [SingletonClass sharedInstance]; [sharedSingleton.photo setPhoto:self.imageView.image]; //Compiler Error: No visible @interface for 'UIImage' declares the selector 'setPhoto' [self.navigationController popViewControllerAnimated:YES]; } |
通过调用
1 2 | UIImage *theImage = sharedSingleton.photo; [theImage setPhoto:self.imageView.image]; |
所以你不是在你的
你可能想要:
然后,我对这个方法有点困惑:
-(空)setphoto:(uiimage*)照片{照片=照片;}
首先,你可能不需要它,因为你有一个
在细节视图中
-(无效)共享照片:(ID)发件人{
1 2 | [[SingletonClass sharedInstance] setPhoto:self.imageView.image]; [self.navigationController popViewControllerAnimated:YES]; |
}
将方法更改为:
1
2
3
4
5 -(void)sharePhoto:(id)sender {
SingletonClass *sharedSingleton = [SingletonClass sharedInstance];
[sharedSingleton setPhoto:self.imageView.image];
//Compiler Error: No visible @interface for 'UIImage' declares the selector 'setPhoto'
[self.navigationController popViewControllerAnimated:YES];
}
使用这一行