右上角的爱心是收藏按钮,白色是未收藏,红色是收藏.
需求是: 用户可以任务点击收藏和取消收藏,如果点了收藏,下次再来到这个页面要显示已收藏状态.
但是我的代码只能做到点击收藏和取消收藏,下次再来到这个页面又变成未收藏状态了(应该是重新判断了代码,所以我想应该要记录下用户的点击状态,如果用nsuserdefaults代码应该如何写?).
以下是我的代码:
-(void)rightBtnClick:(UIButton *)ban {
isCollection = !isCollection;
if (isCollection) {
[self.rightBtn setImage: [UIImage imageNamed: @"collection"] forState: UIControlStateNormal];
} else {
[self.rightBtn setImage: [UIImage imageNamed: @"notCollection"] forState: UIControlStateNormal];
}
}
谢谢~
This usually returns data from the background to tell you whether the product has been collected. If you use UserDefault, you can directly use the product id as the Key and the Value value as a BOOL value to record whether it has been collected.
Then get the value first in viewWillAppear
I think it’s best not to use userDefault to save this kind of thing. userDefault saves the entire dictionary into the plist file. As there are more and more products, the key values of this dictionary will also increase. In the end, we only need to load the collection status of one product, and we have to read a file with tens of thousands of lines, which is very slow.
This is how I usually handle this problem. Do two things when the user clicks the favorite button:
Send collection/cancel collection request to the backend
Update model, update display status instantly
Item 2 can be done manually or with ReactCocoa. Then I guess your problem is that the model in the list page is still not updated, so after returning to the list page and clicking in from the list page, it still shows that it is not updated. My general approach is to use the same object for the model in the details page and the model on the list page. Several key codes:
Go to the details page from the list page:
Note that what is copied here is an object type. The model on the details page and the model in the array on the list page have different pointers pointing to the same object and the same memory, so updating the model on the details page can update the model on the list page at the same time. If you only pass a basic type, such as what you wrote in your description
isCollection
, it will not have this effect.Collect/uncollect in the details page:
When you return to the list page, the model of the list page is also updated. If the list page also displays a heart symbol, you can simply add:
You can update the love logo on the list page.
For this collection, you should modify the server data instead of simply modifying the data locally
I have been doing something similar recently. Can I use ajax background to return the data recorded to the database for likes? How about handling it this way