-(void)addPower:(NSString *)newPower{
newPower = [newPower lowercaseString];
for(int i=0; i<[powers count]; i++){
NSString *p = [powers objectAtIndex:i];
NSString* count = p;
NSRange endRange = [p rangeOfString:@" "];
NSRange searchRange = NSMakeRange(0, endRange.location);
p = [p substringWithRange:searchRange];
endRange = [count rangeOfString:@" "];
count = [count substringWithRange:NSMakeRange(endRange.location, count.length-p.length)];
if([newPower isEqualToString:p]){
NSString *addNewPower = [NSString stringWithFormat:@"%@ %i",newPower,count.integerValue+1];
[powers replaceObjectAtIndex:i withObject:addNewPower];
[ud setValue:addNewPower forKey:productName];
NSLog(@"NEW POWER ADDED: %@ ||| %@\n",addNewPower,productName);
NSLog(@"NEW POWER UD: %@\n",[ud stringForKey:productName]);
}
}
[ud synchronize];
}
输出是;
增加了新功能:捕捉4 |||卡
新电源UD :(空)
当我在手机上重新启动该应用程序后再次加载Userdefault时,它将“snap 4”替换为“1”
我不明白为什么它不保存我的用户默认值。
编辑:
忘了提一下,在初始化程序中设置了ud,我尝试了setObject forKey,仍然得到了相同的结果
最佳答案
如果ud = [NSUserdefaults standardUserDefaults];尝试将ud设置为类的属性,并在类中的所有位置使用self.ud对其进行访问。
在你的.h中
{
NSUserdefaults *ud;
}
@property (nonatomic, weak) NSUserdefaults *ud;
然后在您的.m中
@synthesize ud;
然后当你初始化
self.ud = [NSUserdefaults standardUserDefaults];
关于ios - NSUserdefaults保存空字符串,但字符串不为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15239908/