object sharing among view controllers
I was wondering how can I share a NSDictionary objects among several view controllers which basically are tabs in my application.
I tried using a protocol, like in Java, so that I can cast to the protocol and access the property. That doesn't seem to work.
Also I had a look at similar question at How to share data globally among multiple view controllers
But I observed that the appDelegate method is not safe and may lead to memory leak.
Similarly injection on class A into class B will create the same problem.
So can anyone suggest me any method which i should study or implement in my code?
如果你只想分享Dictionary,为什么不从辅助类中去使用类方法。
+(NSDictionary *)shareMethod
{
return dict;
}
You can use singleton class for sharing the data
Check this Singleton class
MyManger.h
#import <foundation/Foundation.h>
@interface MyManager : NSObject {
NSMutableDictionary *_dict
}
@property (nonatomic, retain) NSMutableDictionary *dict;
+ (id)sharedManager;
@end
MyManger.m
#import "MyManager.h"
static MyManager *sharedMyManager = nil;
@implementation MyManager
@synthesize dict = _dict;
#pragma mark Singleton Methods
+ (id)sharedManager {
@synchronized(self) {
if(sharedMyManager == nil)
sharedMyManager = [[super allocWithZone:NULL] init];
}
return sharedMyManager;
}
- (id)init {
if (self = [super init]) {
dict = [[NSMutableDictionary alloc] init];
}
return self;
}
You can access your dictionary from everywhere like this
[MyManager sharedManager].dict
I found a way out. Since I want a dictionary to be shared across, I declared a method in my protocol
- (void) setSingleHouse:(NSDictionary*) singleHouse;
In each of my controller I implemented the method in a appropriate manner. Hence I was able to share across them for now.
Also I figured out that I was casting in a wrong way earlier ie (@protocol(protocol name)). Now changed it into NSObject .
Sorry for the fuss.
链接地址: http://www.djcxy.com/p/52408.html下一篇: 对象在视图控制器中共享