【问题标题】:Adding Multiple array into single Array in ios在ios中将多个数组添加到单个数组中
【发布时间】:2016-05-20 05:58:48
【问题描述】:

1) 我正在开发一个应用程序,该应用程序包含一个单独的 tableview,并且在该 tableview 上方有一个水平滚动视图,其中包含多个动态按钮,例如 button1、button2...。

2) 在触摸每个按钮时,json 正在启动,我正在使用 NSURLSession.eg. 在 tableview 中解析和显示该 json。按一下 button1 json 就会出现,在触摸 button2 时会出现不同的 json。

3)之后,我想将每个按钮 json 数组存储到单个数组中并相应地显示。例如。假设我点击了 button2 json 将会出现并且应该存储在数组中,以便将来我修改按钮数据应该来自存储的数组。

我已经解决了第 1 点和第 2 点,但不知道如何解决第 3 点。 我还添加了一张图片,可以清楚地了解我的问题。 如果有人有想法,请回复这个问题。在此先感谢。

【问题讨论】:

  • 你可以做的是创建一个数组的集合。你有每个按钮的特殊标识符吗?然后,您可以将其存储在以标识符为键的字典中。否则很难确定哪个数组属于哪个按钮。
  • @TMob 是的,我需要为每个按钮设置特殊的identifer。而且我想在第一次触摸该按钮时将每个按钮数组存储到缓存中,如果我将根据该按钮数组进行修饰,它将来自缓存。您能给我举个例子,如何存储每个动态按钮解析数组进字典
  • @Sandeep 作为标识符,您可以使用数组的索引作为按钮标签。

标签: ios


【解决方案1】:

您可以根据需要使用NSCache 来缓存项目,它的工作方式类似于NSDictionary。

// Init NSCache and declare somewhere as property//you must use singleton approach as well, it's just example i have initialized in viewDidLoad

    - (void)viewDidLoad
    {    
       self.cache = [NSCache alloc] new];
    }

-(void)callApiForKey:(NSString *)buttonName{
        id aObject = [self.cache objectForKey:buttonName]
        if aObject == nil {
          //perform the API call you are talking about
          //after the fetch is preformed and you get data...
          [self.cache setObject: dataObject forKey:buttonName];
          //perform what you need to with said object
        } else {
          //perform operation with cached object
        }
    }

用途:

在您的按钮上单击操作调用上述方法并使用按钮文本: yourButton.titleLabel.text.

[self callApiForKey:yourButton.titleLabel.text];

成为唯一的密钥must。否则你可能会得到/设置错误的数据。

谢谢

【讨论】:

  • 我们可以将每个按钮数组添加到缓存中吗?我试过了,但得到了每个缓存的最后一个触摸按钮数组
  • @Sandeep 我认为您使用的是相同的密钥,因此您可以使用最后一个密钥更新/设置
  • 我希望 subcategoryid 总是不同的。还有你是如何初始化 NSCache 的?
  • "我们可以将每个按钮数组添加到缓存中吗?我尝试过,但获得了每个缓存的最后一个触摸按钮数组——"你能再详细说明一下发生了什么吗?还有一件事是您的 API 响应实际上是在每次单击按钮时返回不同的数据?有时服务器会返回相同的数据用于测试目的
【解决方案2】:
-Each button have a unique tag right? Like button 1 have tag 1, button 2 have tag 2 ,button 3 have tag 3,
-you can manage this thing by Global nsmutabledictionary and nsmutableArray.
-if you click on button 1 before api calling you check 
if(dictionary valueforkey:@"1") (1mean selected button tag)
{
  no need to call api 
  no need to add array in dictionary
  array=[[dictionary valueforkey:@"1"]mutablecopy];(1mean selected button tag)
  [tble reloaddata];

}
else
{
  api calling 
  here you can add array in dictionary
  [dictionary setobject:yourarray forkey:@"1"];
  array=[[dictionary valueforkey:@"1"]mutablecopy];(1mean selected button tag)
  [tble reloaddata];
}

【讨论】:

猜你喜欢
  • 2019-01-25
  • 2014-06-09
  • 2017-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-24
  • 1970-01-01
  • 2011-11-12
相关资源
最近更新 更多