2013-02-19 96 views
0

我想在几个UITableView之间共享一个NSMutableDictionary。重点是,在一个视图中,我可以添加一个数组作为值和字典的相应键,然后设置SingletonObject的字典属性。然后在另一个视图中,我可以通过SingletonObject的属性访问字典中的数组。是否有可能有一个NSMutableDictionary作为SingletonObject的属性?

对于SingletonObject,在头文件中,我有这样的:

@property(nonatomic) NSMutableDictionary * dict; 
+(SingletonObject *) sharedManager; 

在为SingletonObject我有这个实现文件:

@synthesize字典;

+(SingletonObject *)sharedManager static = SingletonObject * sharedResourcesObj = nil;

@synchronized(self) 
{ 
    if (!sharedResourcesObj) 
    { 
     sharedResourcesObj = [[SingletonObject alloc] init]; 
    } 
} 

return sharedResourcesObj; 

}

然后我做了以下我UITTableView类之一

 // instantiate the SingletonObject 
     sharedResourcesObj = [SingletonObject sharedManager]; 

     // instantiate array 
     NSMutableArray *courseDetails = courseDetails = [[NSMutableArray alloc]init]; 
     // put textview value into temp string 
     NSString *tempString = tempString = [[NSString alloc]initWithString:[_txtBuildingRoom text]]; 

     // put textview value into array (via temp string) 
     [courseDetails addObject:tempString]; 

     // set dictionary property of SingletonObject 
     [sharedResourcesObj.dict setObject:courseDetails forKey:_lblCourse.text]; 

的问题是,当我打印的一切出去控制台,一行行,凡事都有一个值并正常工作,除了字典的新值不存在。

当我用下面的代码检查字典的值或计数时,计数为0,字典中没有对象。

 // dictionary count 
     NSLog(@"%i", sharedResourcesObj.dict.count); 

     // get from dictionary 
     NSMutableArray *array = [sharedResourcesObj.dict objectForKey:_lblCourse.text]; 

     // display what is in dictionary 
     for (id obj in array) 
     { 
      NSLog(@"obj: %@", obj); 
     } 

我使用正确的概念在UITableViews之间共享字典吗?

是否存在一些与我的SingletonObject实现有关的问题?

我之前使用SingletonObject的这个实现来共享标签之间的整数值,并且完全没有问题。现在唯一的区别是SingletonObject的属性不是一个整数,而是一个NSMutableDictionary。

任何人都可以帮忙吗?

+1

没有创建字典 – 2013-02-19 06:09:51

回答

1
@synchronized(self) 
{ 
if (!sharedResourcesObj) 
    { 
    sharedResourcesObj = [[SingletonObject alloc] init]; 

    } 
} 

return sharedResourcesObj; 
} 

- (id)init 
{ 
    if (self = [super init]) 
    { 
    _dict = [NSMutableDictionary alloc]init]; 
    } 
    return self; 
} 
+0

我在哪里把init方法? – Zolt 2013-02-19 06:47:01

+0

在你的单例类 – 2013-02-19 06:50:07

+0

[检查此](http:// stackoverflow。com/questions/14831505/create-nsmutabledictionary-that-will-be-available-from-everywhere-in-the-app/14831554#14831554) – 2013-02-19 06:50:37

1

你必须实际上创建字典在你的单身物体,否则它只会是nil。你通常在单身人士的init方法中这样做。

- (id)init 
{ 
    self = [super init]; 
    if (self) { 
     dict = [NSMutableDictionary new]; 
    } 
} 
+0

这是那种我所猜测的问题可能是,但真的不知道或做什么......你说的init方法是什么意思?我会在SingletonObject实现文件中将+(SingletonObject *)sharedManager {}方法放在哪里? – Zolt 2013-02-19 06:43:18

+0

你的意思是把它放在我的UITabableView类的这个方法 - (id)initWithStyle:(UITableViewStyle)风格? – Zolt 2013-02-19 06:49:00

+0

或者在ViewDidLoad中? – Zolt 2013-02-19 06:49:44

相关问题