[英]Check if NSString/NSMutableArray already exists in a NSUserDefault?
I'm making this app with a tableview and stuff. 我正在用一个tableview和东西做这个程序。 I want to make a "Favorites"-tab, and in the detail-view I want to make a star-like button.
我要创建一个“收藏夹”选项卡,并在详细视图中创建一个星形按钮。 I'm done with the "add to favorites" stuff and want to make it impossible to add a string to my favoriteViewController more than once.
我已经完成了“添加到收藏夹”中的工作,并希望不可能多次将字符串添加到我的收藏夹ViewController中。
Basically, I want to check if my NSUserDefaults contains a certain string in its NSMutableArray that matches the indexPath.row in the table view. 基本上,我想检查我的NSUserDefaults是否在其NSMutableArray中包含与表视图中的indexPath.row匹配的某个字符串。 It's really hard to explain...
真的很难解释...
Here's a snippet out of the code. 这是代码片段。 I want to check if the "indexPathRowString" already exists in favoriteKey, before adding it again.
我想先检查“ indexPathRowString”是否已存在于收藏夹中,然后再将其添加。
-(IBAction)addToFavorite:(id)sender {
NSMutableArray* alreadyFavourites = [[[NSUserDefaults standardUserDefaults] objectForKey:@"favoriteKey"] mutableCopy];
[favoritedAlready addObject:indexPathRowString];
[[NSUserDefaults standardUserDefaults] setObject:alreadyFavourites forKey:@"favoriteKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
I'm very thankful for answers, I really need to fix this! 我非常感谢您的回答,我真的需要解决这个问题! :)
:)
You want NSArray's containsObject:
. 您需要NSArray的
containsObject:
:。
Because NSString implements the NSObject Protocol method isEqual:
to return YES
for two strings of the same content, this method will work correctly for you with two different string objects of the same value. 因为NSString实现了NSObject Protocol方法
isEqual:
为相同内容的两个字符串返回YES
,所以该方法将对您使用两个具有相同值的不同字符串对象正常工作。
you can check using 你可以检查使用
if (![favoritedAlready containsObject:indexPathRowString])
{
[favoritedAlready addObject:indexPathRowString];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.