我正在构建一个MVC模型,并且遇到了异常情况,与Apple Documentation相反,尽管您设置了可变对象作为值,“NSUserDefaults返回的值是不可变的。”,但[[NSUserDefaults standardUserDefaults] objectForKey:@"key"]返回一个可变数组。
我在Xcode 4D199中创建了一个空的iOS应用程序,以重新创建条件并确认它不受我的项目中的其他因素的影响。
我设置NSMutableArray如下:
我在Xcode 4D199中创建了一个空的iOS应用程序,以重新创建条件并确认它不受我的项目中的其他因素的影响。
我设置NSMutableArray如下:
- (void)setupTest
{
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
[mutableArray addObject:@"one"];
[mutableArray addObject:@"two"];
[[NSUserDefaults standardUserDefaults] setObject:mutableArray forKey:@"mutableArray_01"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
而且,我得到的对象如下所示:
- (void)checkTest
{
NSMutableArray *mutableArrayInCheck = nil;
id whatIsThis = [[NSUserDefaults standardUserDefaults] objectForKey:@"mutableArray_01"];
if([whatIsThis isKindOfClass:[NSMutableArray class]])
{
NSLog(@"The array is mutable.");
mutableArrayInCheck = (NSMutableArray *)whatIsThis;
}
if([whatIsThis isKindOfClass:[NSArray class]])
{
NSLog(@"The array is immutable.");
}
if ([whatIsThis isMemberOfClass:[NSMutableArray class]])
{
NSLog(@"The array is a member of NSMutableArray class");
}
if (mutableArrayInCheck)
{
[mutableArrayInCheck addObject:@"three"];
NSLog([mutableArrayInCheck description]);
}
}
现在,根据苹果的文档,人们预期控制台只会显示不可变行。但是当我执行代码时,控制台会显示以下行:
2012-01-05 18:47:33.328 Tester_01[78533:f803] The array is mutable.
2012-01-05 18:47:33.348 Tester_01[78533:f803] The array is immutable.
2012-01-05 18:47:33.349 Tester_01[78533:f803] (
one,
two,
three
)
我想知道我是否漏掉了什么。
额外信息,执行测试的代码如下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
BOOL setupKey = NO;
if (setupKey)
{
[self setupTest];
}
BOOL checkKey = YES;
if (checkKey)
{
[self checkTest];
}
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
最初,我运行了带有setupKey设置为YES的项目。第一次运行后,我将setupKey更改为NO。控制台日志是在setupKey设置为NO时生成的结果。请告诉我您的想法。
NSMutableArray
分配给NSArray
指针,因为使用[NSArray arrayWithArray:mutableArray]
只会增加开销,而几乎没有什么好处。 - mvds