一个低级错误犯了两次,我觉得必须去记录下了。
OC
第一次犯错误的时候,是用oc的时候出现的:
目的:用_categoryArray保存内容,将_categoryArray里面的内容放到_rowsDictionary中,然后将_categoryArray内容清空,以方便下次在保存内容
_rowsDictionary = [NSMutableDictionary new];
_categoryArray = [NSMutableArray new];
//1、放置内容
[_rowsDictionary setObject:_categoryArray forKey:key];
//2、加入到Dictionary就要清空数据
[_categoryArray removeAllObjects]; //错误就出现在这里,将_categoryArray这个内容清空之后,发现_rowsDictionary这个里面的内容也都是没有了。
_categoryArray = [NSMutableArray new];//最好采用这种方式。没有想到有什么其他更好的方式。
原因:
_categoryArray为引用类型,在于_rowsDictionary对应的key的集合和_categoryArray是共享同一块数据,所以当把_categoryArray里面的内容清空之后,_rowsDictionary对应的key下面的内容也是清空的。
好吧,出现了这一次之后,在写java的时候,发现自己又一次被这个问题折腾了好长时间。
Java
A对象中含有:
private List<String> attrList;
private List<String> aViewList;
我在B对象中对A对象的该两个集合进行赋值:
A a = new A();
a.attrList = bAttrList;
a.aViewList = bViewList;
同样,我又一次的悲剧重演
bAttrList.clear();
bViewList.clear();
然后同样在查看A对象中的attrList和aViewList始终为空集合。问题和oc的那个问题是一样的。所以当犯了两次错误之后,我必须要记录下,防止以后在发生,以提醒自己!!!!!
Android
自己突然又想到之前遇到的ListView和Adapter的一个问题,之前只知道那样会出现报错The content of the adapter has changed but ListView did not recive notification
。
出现这个问题的代码:
ListView listView;
List<String> dataSource = new ArrayList<>();
xxAdapter adapter= new xxAdapter(context,dataSource);
//从服务器中获取数据之后在子线程更新dataSource
dataSource = serverData;
adapter.notifyDataSetChanged();
//当多次从服务器请求数据的时候,就会修改serverData里的内容。就会抛出The content of the adapter has changed but ListView did not recive notification这个异常。
其实这个问题和上面两个问题是一样的。dataSource和serverData是共用内存地址的,所以修改serverData的数据同样会去修改dataSource的数据内容的,在服务器获取数据之后,在子线程中修改数据之后,就会修改dataSource的数据,但是修改了dataSource的数据却没有及时调用adapter.notifyDataSetChanged()这个方法,引起了报错。因此在项目中一般采用下面的方式进行避免该问题:
serverContainer // server的数据源的容器
serverContainer.addAll(serverData);
dataSource.clear();
dataSource.addAll(serverContainer);
adapter.notifyDataSetChanged();
这样就可以很好的避免该问题了。